package com.dzl.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.dzl.admin.pojo.dto.SendMsgDto;
import com.dzl.admin.pojo.vo.LoginSysAdminVo;
import com.dzl.api.pojo.Order;
import com.dzl.api.service.BlueBrothersService;
import com.dzl.api.service.ExtractCardService;
import com.dzl.base.service.BaseServiceImpl;
import com.dzl.card.pojo.WelfareCardSecret;
import com.dzl.card.pojo.vo.WelfareUserCardSecretVo;
import com.dzl.card.service.WelfareCardSecretService;
import com.dzl.config.database.Master;
import com.dzl.config.exception.CommonException;
import com.dzl.constant.*;
import com.dzl.enterprise.pojo.WelfareEnterprise;
import com.dzl.enterprise.service.WelfareEnterpriseService;
import com.dzl.exchange.pojo.WelfareExchangeSecret;
import com.dzl.exchange.pojo.vo.WelfareExchangeWithSecretVo;
import com.dzl.exchange.service.WelfareExchangeSecretService;
import com.dzl.express.pojo.WelfareExpress;
import com.dzl.express.service.WelfareExpressService;
import com.dzl.fee.pojo.vo.WelfareFeeSalesCustomersNameVo;
import com.dzl.fee.service.WelfareFeeOrderService;
import com.dzl.finance.pojo.WelfareFinancePayment;
import com.dzl.finance.pojo.WelfareFinancePaymentRecord;
import com.dzl.finance.service.WelfareFinancePaymentRecordService;
import com.dzl.finance.service.WelfareFinancePaymentService;
import com.dzl.goods.pojo.WelfareGoods;
import com.dzl.goods.pojo.WelfareGoodsAttr;
import com.dzl.goods.service.WelfareGoodsAttrService;
import com.dzl.goods.service.WelfareGoodsService;
import com.dzl.integral.pojo.WelfareIntegralGrantDetail;
import com.dzl.integral.service.WelfareIntegralGrantDetailService;
import com.dzl.manager.ManagerService;
import com.dzl.operation.service.OperationLogService;
import com.dzl.order.dao.WelfareOrderMapper;
import com.dzl.order.pojo.*;
import com.dzl.order.pojo.dto.*;
import com.dzl.order.pojo.query.WelfareOrderQuery;
import com.dzl.order.pojo.query.WelfareOrderUserQuery;
import com.dzl.order.pojo.vo.*;
import com.dzl.order.service.*;
import com.dzl.supplier.pojo.WelfareSupplier;
import com.dzl.supplier.service.WelfareSupplierService;
import com.dzl.userwx.pojo.WelfareUserWx;
import com.dzl.userwx.service.WelfareUserPurchasesNumService;
import com.dzl.userwx.service.WelfareUserWxService;
import com.dzl.util.*;
import com.dzl.util.wx.WxConfig;
import com.dzl.util.wx.wxpay.WXPayConstants;
import com.dzl.util.wx.wxpay.WXPayUtil;
import com.dzl.voucherSecret.pojo.WelfareVoucherSecret;
import com.dzl.voucherSecret.service.WelfareVoucherSecretService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.Sqls;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * 订单表(WelfareOrder)表服务实现类
 * @author caobucao
 * @since 2021-05-18 15:36:51
 */
@Slf4j
@Service("welfareOrderService")
public class WelfareOrderServiceImpl extends BaseServiceImpl<WelfareOrder> implements WelfareOrderService {

    @Autowired
    private WelfareOrderMapper mapper;
    @Autowired
    private WelfareOrderGoodsService welfareOrderGoodsService;
    @Autowired
    private WelfareGoodsAttrService welfareGoodsAttrService;
    @Autowired
    private WelfareGoodsService welfareGoodsService;
    @Autowired
    private WelfareOrderAddressService welfareOrderAddressService;
    @Autowired
    private WelfareCardSecretService welfareCardSecretService;
    @Autowired
    private WelfareOrderExpressService welfareOrderExpressService;
    @Autowired
    private WelfareExpressService welfareExpressService;
    @Autowired
    private OperationLogService operationLogService;
    @Autowired
    private WelfareVoucherSecretService welfareVoucherSecretService;
    @Autowired
    private WelfareExchangeSecretService welfareExchangeSecretService;
    @Autowired
    private WelfareUserWxService welfareUserWxService;
    @Autowired
    private BlueBrothersService blueBrothersService;
    @Autowired
    private ManagerService managerService;
    @Autowired
    private WelfareOrderTempRemarkService welfareOrderTempRemarkService;
    @Autowired
    private WelfareIntegralGrantDetailService welfareIntegralGrantDetailService;
    @Autowired
    private OrderAddPhysicalService orderAddPhysicalService;
    @Autowired
    private OrderAddExchangeService orderAddExchangeService;
    @Autowired
    private OrderAddVirtualService orderAddVirtualService;
    @Autowired
    private OrderAddApiRechargeService orderAddApiRechargeService;
    @Autowired
    private OrderAddApiExtractCardService orderAddApiExtractCardService;
    @Autowired
    private WelfareFeeOrderService welfareFeeOrderService;
    @Autowired
    private WelfareFinancePaymentRecordService welfareFinancePaymentRecordService;
    @Autowired
    private WelfareFinancePaymentService welfareFinancePaymentService;
    @Autowired
    private ExtractCardService extractCardService;
    @Autowired
    private WelfareOrderApiCardService welfareOrderApiCardService;
    @Autowired
    private WelfareUserPurchasesNumService welfareUserPurchasesNumService;
    @Autowired
    private WelfareSupplierService welfareSupplierService;
    @Autowired
    private WelfareEnterpriseService welfareEnterpriseService;


    // 最小均摊阈值
    private final BigDecimal MIN_SHARE_PRICE = BigDecimal.valueOf(0.1);

    @Override
    public PageInfo<WelfareOrderParentVo> getOrderListPage(WelfareOrderQuery query) {
        PageHelper.startPage(query);
        // 先查询父订单列表
        List<WelfareOrderParentVo> parentOrderList = mapper.getOrderParentListPage(query);
        for (WelfareOrderParentVo welfareOrderParentVo : parentOrderList) {
            List<WelfareOrderSupplierVo> childOrderVoList;
            if (welfareOrderParentVo.getStatus().equals(0)) {
                // 拆单了的
                query.setOldId(welfareOrderParentVo.getId());
                query.setId(null);
            } else {
                // 未拆单的
                query.setId(welfareOrderParentVo.getId());
                query.setOldId(null);
            }
            if(EmptyUtils.isNotEmpty(welfareOrderParentVo.getOrderType()) && welfareOrderParentVo.getOrderType()==WelfareOrderEnum.ORDER_TYPE_ENTERPRISE_API.getCode()){
                welfareOrderParentVo.setOrderSourceType("API");
            }else{
                welfareOrderParentVo.setOrderSourceType("小程序");
            }
            childOrderVoList = mapper.getOrderChildList(query);
            for (WelfareOrderSupplierVo welfareOrderChildVo : childOrderVoList) {
                if(EmptyUtils.isEmpty(welfareOrderChildVo.getDeliveryUserName())){
                    // 3.4.7
                    if (welfareOrderChildVo.getOrderStatus().equals(WelfareOrderEnum.ORDER_STATUS_SHIPED.getCode())
                            || welfareOrderChildVo.getOrderStatus().equals(WelfareOrderEnum.ORDER_STATUS_COMPLETED.getCode())
                            ||welfareOrderChildVo.getOrderStatus().equals(WelfareOrderEnum.ORDER_STATUS_DELIVERY_REFUND.getCode())
                    ) {
                        welfareOrderChildVo.setDeliveryUserName("商家");
                    } else {
                        welfareOrderChildVo.setDeliveryUserName("-");
                    }
                }
                //判断是否API订单，若是api订单，则orderRemark取值要通过###分隔解析一下
                if(EmptyUtils.isNotEmpty(welfareOrderChildVo.getOrderType()) && welfareOrderChildVo.getOrderType() == WelfareOrderEnum.ORDER_TYPE_ENTERPRISE_API.getCode()){
                    welfareOrderChildVo.setOrderRemark("");
                    if(EmptyUtils.isNotEmpty(welfareOrderChildVo.getOrderRemark())){
                        String[] orderRemark_ = welfareOrderChildVo.getOrderRemark().split("###");
                        if(orderRemark_.length==2 && EmptyUtils.isNotEmpty(orderRemark_[1]) && !orderRemark_[1].equals("null")){
                            welfareOrderChildVo.setOrderRemark(orderRemark_[1]);
                        }
                    }
                }
                // 拼接收货地址
                StringBuilder consigneeAddress = new StringBuilder();
                if (EmptyUtils.isNotEmpty(welfareOrderChildVo.getProvince())) {
                    consigneeAddress.append(welfareOrderChildVo.getProvince());
                }
                if (EmptyUtils.isNotEmpty(welfareOrderChildVo.getCity())) {
                    consigneeAddress.append(welfareOrderChildVo.getCity());
                }
                if (EmptyUtils.isNotEmpty(welfareOrderChildVo.getArea())) {
                    consigneeAddress.append(welfareOrderChildVo.getArea());
                }
                if (EmptyUtils.isNotEmpty(welfareOrderChildVo.getAddress())) {
                    consigneeAddress.append(welfareOrderChildVo.getAddress());
                }
                if (EmptyUtils.isNotEmpty(consigneeAddress)) {
                    welfareOrderChildVo.setConsigneeInfo(consigneeAddress.toString());
                }
                BigDecimal paymentAmount = welfareOrderChildVo.getPaymentAmount();
                // 如果补差金额为0，不展示微信支付流水号，
                if (!(EmptyUtils.isNotEmpty(paymentAmount) && paymentAmount.compareTo(BigDecimal.ZERO) == 1)) {
                    welfareOrderChildVo.setOtherTradeNo("-");
                }
                // 如果是兑换订单，不展示微信支付流水号，并且将补差金额设置为0
                if (EmptyUtils.isNotEmpty(welfareOrderChildVo.getOrderType()) && welfareOrderChildVo.getOrderType().equals(4)) {
                    welfareOrderChildVo.setOtherTradeNo("-");
                }
                List<WelfareOrderGoodsVo> orderGoodsVoList = welfareOrderGoodsService.selectOrderGoodsVoByOrderId(welfareOrderChildVo.getId());
                if (EmptyUtils.isNotEmpty(orderGoodsVoList) && orderGoodsVoList.size() > 0) {
                    welfareOrderChildVo.setOrderGoodsVoList(orderGoodsVoList);
                    for (WelfareOrderGoodsVo welfareOrderGoodsVo : orderGoodsVoList) {
                        // 处理兑换订单不展示均摊信息
                        if (EmptyUtils.isNotEmpty(welfareOrderChildVo.getOrderType()) && welfareOrderChildVo.getOrderType().equals(WelfareOrderEnum.ORDER_TYPE_EXCHANGE.getCode())) {
                            welfareOrderGoodsVo.setPaymentCredits(null);
                            welfareOrderGoodsVo.setPaymentAmount(null);
                        }
                        if (EmptyUtils.isNotEmpty(welfareOrderChildVo.getOrderStatus()) && (WelfareOrderEnum.ORDER_STATUS_UNPAY.getCode().equals(welfareOrderChildVo.getOrderStatus()) || WelfareOrderEnum.ORDER_STATUS_CANCEL.getCode().equals(welfareOrderChildVo.getOrderStatus()))) {
                            welfareOrderGoodsVo.setPaymentCredits(null);
                            welfareOrderGoodsVo.setPaymentAmount(null);
                        }
                        welfareOrderGoodsVo.setSupplyPrice(welfareOrderGoodsVo.getCreditsAmount());
                        welfareOrderGoodsVo.setSupplyTotalPrice(welfareOrderGoodsVo.getCreditTotalAmount());
                        // 拼接商品信息
                        StringBuilder goodsDetail = new StringBuilder();
                        if (EmptyUtils.isNotEmpty(welfareOrderGoodsVo.getFirstDetailName())) {
                            goodsDetail.append(welfareOrderGoodsVo.getFirstDetailName());
                        }
                        if (EmptyUtils.isNotEmpty(welfareOrderGoodsVo.getSecondDetailName())) {
                            goodsDetail.append("/");
                            goodsDetail.append(welfareOrderGoodsVo.getSecondDetailName());
                        }
                        if (EmptyUtils.isNotEmpty(welfareOrderGoodsVo.getThirdDetailName())) {
                            goodsDetail.append("/");
                            goodsDetail.append(welfareOrderGoodsVo.getThirdDetailName());
                        }
                        welfareOrderGoodsVo.setGoodsDetails(goodsDetail.toString());

                        //判断是卡支付还是兑换券支付
                        if(EmptyUtils.isNotEmpty(welfareOrderGoodsVo.getCardSecretId())){
                            //如果是卡支付
                            WelfareUserCardSecretVo welfareCardSecret = welfareCardSecretService.getUserCardBindInfo(welfareOrderGoodsVo.getCardSecretId());
                            if(EmptyUtils.isNotEmpty(welfareCardSecret)){
                                welfareOrderGoodsVo.setBatchNumber(welfareCardSecret.getCardBatchNumber());
                                welfareOrderGoodsVo.setCardNo(welfareCardSecret.getNumber());
                                if(EmptyUtils.isNotEmpty(welfareCardSecret.getFeeOrderId())){
                                    WelfareFeeSalesCustomersNameVo salesCustomersNameVo = welfareFeeOrderService.selectSalesCustomersNameVoByFeeOrderId(welfareCardSecret.getFeeOrderId());
                                    if(EmptyUtils.isNotEmpty(salesCustomersNameVo)){
                                        welfareOrderGoodsVo.setCustomersName(salesCustomersNameVo.getCustomersName());
                                        welfareOrderGoodsVo.setSalesName(salesCustomersNameVo.getSalesName());
                                    }
                                }
                            }
                        }else if(EmptyUtils.isNotEmpty(welfareOrderChildVo.getExchangeSecretId())){
                            //如果是兑换券支付
                            WelfareExchangeWithSecretVo welfareExchangeSecret = welfareExchangeSecretService.getExchangeInfoByExchangeSecretId(welfareOrderChildVo.getExchangeSecretId());
                            if(EmptyUtils.isNotEmpty(welfareExchangeSecret)){
                                welfareOrderGoodsVo.setBatchNumber(welfareExchangeSecret.getExchangeBatchNumber());
                                welfareOrderGoodsVo.setExchangeNo(welfareExchangeSecret.getNumber());
                                if(EmptyUtils.isNotEmpty(welfareExchangeSecret.getFeeOrderId())){
                                    WelfareFeeSalesCustomersNameVo salesCustomersNameVo = welfareFeeOrderService.selectSalesCustomersNameVoByFeeOrderId(welfareExchangeSecret.getFeeOrderId());
                                    if(EmptyUtils.isNotEmpty(salesCustomersNameVo)){
                                        welfareOrderGoodsVo.setCustomersName(salesCustomersNameVo.getCustomersName());
                                        welfareOrderGoodsVo.setSalesName(salesCustomersNameVo.getSalesName());
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (EmptyUtils.isNotEmpty(childOrderVoList) && childOrderVoList.size() > 0) {
                if (EmptyUtils.isNotEmpty(childOrderVoList.get(0).getSupplierName())) {
                    welfareOrderParentVo.setSupplierName(childOrderVoList.get(0).getSupplierName());
                }
                if (EmptyUtils.isNotEmpty(childOrderVoList.get(0).getEnterpriseName())) {
                    welfareOrderParentVo.setEnterpriseName(childOrderVoList.get(0).getEnterpriseName());
                }
            }
            welfareOrderParentVo.setChildOrderVoList(childOrderVoList);
        }
        PageInfo<WelfareOrderParentVo> page = new PageInfo<WelfareOrderParentVo>(parentOrderList);
        return page;
    }

    @Override
    public List<WelfareOrderSupplierVo> getOrderChildList(WelfareOrderQuery query) {
        List<WelfareOrderSupplierVo> childOrderVoList = mapper.getOrderChildList(query);
        for (WelfareOrderSupplierVo welfareOrderChildVo : childOrderVoList) {
            if(EmptyUtils.isEmpty(welfareOrderChildVo.getDeliveryUserName())){
                // 3.4.7
                if (welfareOrderChildVo.getOrderStatus().equals(WelfareOrderEnum.ORDER_STATUS_SHIPED.getCode())
                        || welfareOrderChildVo.getOrderStatus().equals(WelfareOrderEnum.ORDER_STATUS_COMPLETED.getCode())
                        ||welfareOrderChildVo.getOrderStatus().equals(WelfareOrderEnum.ORDER_STATUS_DELIVERY_REFUND.getCode())
                ) {
                    welfareOrderChildVo.setDeliveryUserName("商家");
                } else {
                    welfareOrderChildVo.setDeliveryUserName("-");
                }
            }
            //判断是否API订单，若是api订单，则orderRemark取值要通过###分隔解析一下
            if(EmptyUtils.isNotEmpty(welfareOrderChildVo.getOrderType()) && welfareOrderChildVo.getOrderType() == WelfareOrderEnum.ORDER_TYPE_ENTERPRISE_API.getCode()){
                welfareOrderChildVo.setOrderRemark("");
                if(EmptyUtils.isNotEmpty(welfareOrderChildVo.getOrderRemark())){
                    String[] orderRemark_ = welfareOrderChildVo.getOrderRemark().split("###");
                    if(orderRemark_.length==2 && EmptyUtils.isNotEmpty(orderRemark_[1]) && !orderRemark_[1].equals("null")){
                        welfareOrderChildVo.setOrderRemark(orderRemark_[1]);
                    }
                }
            }
            // 拼接收货地址
            StringBuilder consigneeAddress = new StringBuilder();
            if (EmptyUtils.isNotEmpty(welfareOrderChildVo.getProvince())) {
                consigneeAddress.append(welfareOrderChildVo.getProvince());
            }
            if (EmptyUtils.isNotEmpty(welfareOrderChildVo.getCity())) {
                consigneeAddress.append(welfareOrderChildVo.getCity());
            }
            if (EmptyUtils.isNotEmpty(welfareOrderChildVo.getArea())) {
                consigneeAddress.append(welfareOrderChildVo.getArea());
            }
            if (EmptyUtils.isNotEmpty(welfareOrderChildVo.getAddress())) {
                consigneeAddress.append(welfareOrderChildVo.getAddress());
            }
            if (EmptyUtils.isNotEmpty(consigneeAddress)) {
                welfareOrderChildVo.setConsigneeInfo(consigneeAddress.toString());
            }
            BigDecimal paymentAmount = welfareOrderChildVo.getPaymentAmount();
            // 如果补差金额为0，不展示微信支付流水号，
            if (!(EmptyUtils.isNotEmpty(paymentAmount) && paymentAmount.compareTo(BigDecimal.ZERO) == 1)) {
                welfareOrderChildVo.setOtherTradeNo("-");
            }
            // 如果是兑换订单，不展示微信支付流水号，并且将补差金额设置为0
            if (EmptyUtils.isNotEmpty(welfareOrderChildVo.getOrderType()) && welfareOrderChildVo.getOrderType().equals(4)) {
                welfareOrderChildVo.setOtherTradeNo("-");
            }
            List<WelfareOrderGoodsVo> orderGoodsVoList = welfareOrderGoodsService.selectOrderGoodsVoByOrderId(welfareOrderChildVo.getId());
            if (EmptyUtils.isNotEmpty(orderGoodsVoList) && orderGoodsVoList.size() > 0) {
                welfareOrderChildVo.setOrderGoodsVoList(orderGoodsVoList);
                for (WelfareOrderGoodsVo welfareOrderGoodsVo : orderGoodsVoList) {
                    // 处理兑换订单不展示均摊信息
                    if (EmptyUtils.isNotEmpty(welfareOrderChildVo.getOrderType()) && welfareOrderChildVo.getOrderType().equals(WelfareOrderEnum.ORDER_TYPE_EXCHANGE.getCode())) {
                        welfareOrderGoodsVo.setPaymentCredits(null);
                        welfareOrderGoodsVo.setPaymentAmount(null);
                    }
                    if (EmptyUtils.isNotEmpty(welfareOrderChildVo.getOrderStatus()) && (WelfareOrderEnum.ORDER_STATUS_UNPAY.getCode().equals(welfareOrderChildVo.getOrderStatus()) || WelfareOrderEnum.ORDER_STATUS_CANCEL.getCode().equals(welfareOrderChildVo.getOrderStatus()))) {
                        welfareOrderGoodsVo.setPaymentCredits(null);
                        welfareOrderGoodsVo.setPaymentAmount(null);
                    }
                    welfareOrderGoodsVo.setSupplyPrice(welfareOrderGoodsVo.getCreditsAmount());
                    welfareOrderGoodsVo.setSupplyTotalPrice(welfareOrderGoodsVo.getCreditTotalAmount());
                    // 拼接商品信息
                    StringBuilder goodsDetail = new StringBuilder();
                    if (EmptyUtils.isNotEmpty(welfareOrderGoodsVo.getFirstDetailName())) {
                        goodsDetail.append(welfareOrderGoodsVo.getFirstDetailName());
                    }
                    if (EmptyUtils.isNotEmpty(welfareOrderGoodsVo.getSecondDetailName())) {
                        goodsDetail.append("/");
                        goodsDetail.append(welfareOrderGoodsVo.getSecondDetailName());
                    }
                    if (EmptyUtils.isNotEmpty(welfareOrderGoodsVo.getThirdDetailName())) {
                        goodsDetail.append("/");
                        goodsDetail.append(welfareOrderGoodsVo.getThirdDetailName());
                    }
                    welfareOrderGoodsVo.setGoodsDetails(goodsDetail.toString());
                    //判断是卡支付还是兑换券支付
                    if(EmptyUtils.isNotEmpty(welfareOrderGoodsVo.getCardSecretId())){
                        //如果是卡支付
                        WelfareUserCardSecretVo welfareCardSecret = welfareCardSecretService.getUserCardBindInfo(welfareOrderGoodsVo.getCardSecretId());
                        if(EmptyUtils.isNotEmpty(welfareCardSecret)){
                            welfareOrderGoodsVo.setBatchNumber(welfareCardSecret.getCardBatchNumber());
                            welfareOrderGoodsVo.setCardNo(welfareCardSecret.getNumber());
                            if(EmptyUtils.isNotEmpty(welfareCardSecret.getFeeOrderId())){
                                WelfareFeeSalesCustomersNameVo salesCustomersNameVo = welfareFeeOrderService.selectSalesCustomersNameVoByFeeOrderId(welfareCardSecret.getFeeOrderId());
                                if(EmptyUtils.isNotEmpty(salesCustomersNameVo)){
                                    welfareOrderGoodsVo.setCustomersName(salesCustomersNameVo.getCustomersName());
                                    welfareOrderGoodsVo.setSalesName(salesCustomersNameVo.getSalesName());
                                }
                            }
                        }
                    }else if(EmptyUtils.isNotEmpty(welfareOrderChildVo.getExchangeSecretId())){
                        //如果是兑换券支付
                        WelfareExchangeWithSecretVo welfareExchangeSecret = welfareExchangeSecretService.getExchangeInfoByExchangeSecretId(welfareOrderChildVo.getExchangeSecretId());
                        if(EmptyUtils.isNotEmpty(welfareExchangeSecret)){
                            welfareOrderGoodsVo.setBatchNumber(welfareExchangeSecret.getExchangeBatchNumber());
                            welfareOrderGoodsVo.setExchangeNo(welfareExchangeSecret.getNumber());
                            if(EmptyUtils.isNotEmpty(welfareExchangeSecret.getFeeOrderId())){
                                WelfareFeeSalesCustomersNameVo salesCustomersNameVo = welfareFeeOrderService.selectSalesCustomersNameVoByFeeOrderId(welfareExchangeSecret.getFeeOrderId());
                                if(EmptyUtils.isNotEmpty(salesCustomersNameVo)){
                                    welfareOrderGoodsVo.setCustomersName(salesCustomersNameVo.getCustomersName());
                                    welfareOrderGoodsVo.setSalesName(salesCustomersNameVo.getSalesName());
                                }
                            }
                        }
                    }
                }
            }
        }
        return childOrderVoList;
    }

    @Override
    public List<Integer> getOrderCount(WelfareOrderQuery query) {
        return mapper.getOrderCount(query);
    }

    @Override
    public void exportOrderList(List<WelfareOrderSupplierVo> list, HttpServletResponse res, HttpServletRequest req) {
        List<List<String>> data = new ArrayList<>();
        boolean showOrderStatus = false;
        if(EmptyUtils.isNotEmpty(list)) {
            for(WelfareOrderSupplierVo x : list) {
                for(WelfareOrderGoodsVo y : x.getOrderGoodsVoList()) {
                    List<String> rowData = new ArrayList<>();
                    rowData.add(x.getOrderNo());
                    rowData.add(x.getOrderTypeName());
                    rowData.add(DateUtil.format2DateTime(x.getCreateTime()));
                    if(x.getOrderStatus()==WelfareOrderEnum.ORDER_STATUS_SHIPED.getCode() || x.getOrderStatus()==WelfareOrderEnum.ORDER_STATUS_COMPLETED.getCode()
                            || x.getOrderStatus()==WelfareOrderEnum.ORDER_STATUS_CANCEL.getCode() || x.getOrderStatus()==WelfareOrderEnum.ORDER_STATUS_NO_DELIVERY_REFUND.getCode()
                            || x.getOrderStatus()==WelfareOrderEnum.ORDER_STATUS_DELIVERY_REFUND.getCode()){
                        rowData.add(x.getOrderStatusName());
                        showOrderStatus = true;
                    }
                    rowData.add(x.getSupplierName());
                    rowData.add(y.getGoodsName());
                    rowData.add(y.getGoodsDetails());
                    rowData.add(y.getCostPrice()+"");
                    rowData.add(y.getCreditsAmount()+"");
                    rowData.add(y.getGoodsQuantity()+"");
                    rowData.add(y.getCostTotalPrice().toString());
                    rowData.add(y.getSupplyTotalPrice().toString());
                    rowData.add(x.getSignDes());
                    rowData.add(x.getConsigneeName());
                    rowData.add(x.getConsigneePhone());
                    rowData.add(x.getConsigneeInfo());
                    if(x.getOrderStatus()==WelfareOrderEnum.ORDER_STATUS_SHIPED.getCode() || x.getOrderStatus()==WelfareOrderEnum.ORDER_STATUS_COMPLETED.getCode()){
                        List<WelfareOrderExpressVo> expresslist = welfareOrderExpressService.getOrderExpressInfo(x.getId());
                        StringBuffer expressName = new StringBuffer();
                        StringBuffer expressNo = new StringBuffer();
                        if(EmptyUtils.isNotEmpty(expresslist)){
                            expresslist.forEach(z->{
                                expressName.append(z.getExpressName()).append(",");
                                expressNo.append(z.getExpressNo()).append(",");
                            });
                            rowData.add(expressName.substring(0,expressName.length()-1));
                            rowData.add(expressNo.substring(0,expressNo.length()-1));
                        }else{
                            rowData.add("");
                            rowData.add("");
                        }
                    }
                    data.add(rowData);
                }
            }
        }
        OutputStream os = null;
        try{
            HSSFWorkbook workbook = new HSSFWorkbook();
            String fileName = "常规订单" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xls";
            res.setHeader("Content-disposition", "attachment; filename=" + fileName);
            res.setContentType("application/vnd.ms-excel;charset=utf-8");
            os = res.getOutputStream();
            if(showOrderStatus){
                String[] headers = {"订单编号","订单类型","下单时间","订单状态","供应商名称","商品名称","商品规格","成本价","供应价","商品数量",
                        "成本价合计","供应价合计","订单标记","收货联系人","联系人手机","收货地址","物流公司","物流单号/备注"};
                ExcelUtil.exportExcel(workbook, 0, "Page1", headers, data, os);
            }else{
                String[] headers = {"订单编号","订单类型","下单时间","供应商名称","商品名称","商品规格","成本价","供应价","商品数量",
                        "成本价合计","供应价合计","订单标记","收货联系人","联系人手机","收货地址","物流公司","物流单号/备注"};
                ExcelUtil.exportExcel(workbook, 0, "Page1", headers, data, os);
            }
            workbook.write(os);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                assert os != null;
                os.flush();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void exportSaleFlow(List<WelfareOrderSupplierVo> list, HttpServletResponse res, HttpServletRequest req) {
        List<List<String>> data = new ArrayList<>();
        if(EmptyUtils.isNotEmpty(list)) {
            for(WelfareOrderSupplierVo x : list) {
                for(WelfareOrderGoodsVo y : x.getOrderGoodsVoList()) {
                    List<String> rowData = new ArrayList<>();
                    rowData.add(x.getOrderNo());
                    rowData.add(x.getOrderTypeName());
                    rowData.add(DateUtil.format2DateTime(x.getCreateTime()));
                    rowData.add(x.getOrderStatusName());
                    rowData.add(x.getSupplierName());
                    rowData.add(y.getGoodsName());
                    rowData.add(y.getGoodsDetails());
                    rowData.add(y.getGoodsQuantity()+"");
                    rowData.add(y.getCreditsAmount()+"");
                    rowData.add(y.getCostPrice()+"");
                    rowData.add(y.getSupplyPrice()+"");
                    rowData.add(x.getSignDes());
                    rowData.add(x.getCreditsAmount().toString());
                    rowData.add(x.getPaymentAmount().toString());
                    if (EmptyUtils.isEmpty(y.getCardNo()) && EmptyUtils.isEmpty(y.getExchangeNo())) {
                        rowData.add("-");
                    } else {
                        StringBuffer sb = new StringBuffer();
                        if(EmptyUtils.isNotEmpty(y.getCardNo())){
                            sb.append(y.getCardNo());
                        }
                        if(EmptyUtils.isNotEmpty(y.getExchangeNo())){
                            sb.append(y.getExchangeNo());
                        }
                        rowData.add(sb.toString());
                    }
                    rowData.add(EmptyUtils.isNotEmpty(x.getOtherTradeNo())?x.getOtherTradeNo():"-");
                    if (x.getOrderStatus()==WelfareOrderEnum.ORDER_STATUS_NO_DELIVERY_REFUND.getCode() || x.getOrderStatus()==WelfareOrderEnum.ORDER_STATUS_DELIVERY_REFUND.getCode()) {
                        rowData.add(DateUtil.format2DateTime(x.getUpdateTime()));
                    } else {
                        rowData.add("-");
                    }
                    rowData.add(EmptyUtils.isNotEmpty(y.getCustomersName())?y.getCustomersName():"-");
                    rowData.add(EmptyUtils.isNotEmpty(y.getSalesName())?y.getSalesName():"-");
                    rowData.add(EmptyUtils.isNotEmpty(y.getBatchNumber())?y.getBatchNumber():"-");
                    data.add(rowData);
                }
            }
        }
        OutputStream os = null;
        try{
            HSSFWorkbook workbook = new HSSFWorkbook();
            String fileName = "常规订单销售流水" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xls";
            res.setHeader("Content-disposition", "attachment; filename=" + fileName);
            res.setContentType("application/vnd.ms-excel;charset=utf-8");
            os = res.getOutputStream();
            String[] headers = {"订单编号","订单类型","下单时间","订单状态","供应商名称","商品名称","商品规格","商品数量","商品销售价","商品成本价","商品供应价",
                    "订单标记","用户支付福力","用户补差","支付卡号/兑换券号","微信流水号","退款时间","客户名称","销售员","批次号"};
            ExcelUtil.exportExcel(workbook, 0, "Page1", headers, data, os);
            workbook.write(os);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                assert os != null;
                os.flush();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public List<WelfareOrderSupplierVo> getOrderGoodsListByUserId(WelfareOrderUserQuery query) {
        PageHelper.startPage(query);
        List<WelfareOrderSupplierVo> list = mapper.getOrderGoodsListByUserId(query);
        for (WelfareOrderSupplierVo welfareOrderGoodsListVo : list) {
            if (EmptyUtils.isNotEmpty(welfareOrderGoodsListVo.getOrderStatus()) && welfareOrderGoodsListVo.getOrderStatus().equals(WelfareOrderEnum.ORDER_STATUS_DELIVERY_REFUND.getCode())) {
                welfareOrderGoodsListVo.setOrderStatus(WelfareOrderEnum.ORDER_STATUS_NO_DELIVERY_REFUND.getCode());
            }
            if (EmptyUtils.isNotEmpty(welfareOrderGoodsListVo.getOrderStatus()) && welfareOrderGoodsListVo.getOrderStatus().equals(WelfareOrderEnum.ORDER_STATUS_PRE_PAID.getCode())) {
                welfareOrderGoodsListVo.setOrderStatus(WelfareOrderEnum.ORDER_STATUS_PAID.getCode());
            }
            List<WelfareOrderGoodsVo> orderGoodsVoList = welfareOrderGoodsService.selectOrderGoodsVoByOrderId(welfareOrderGoodsListVo.getId());
            welfareOrderGoodsListVo.setOrderGoodsVoList(orderGoodsVoList);
        }
        return list;
    }

    @Override
    public WelfareOrderDetailVo getOrderDetailByOrderId(Integer orderId, Integer dataPort) {
        //查询订单详情
        WelfareOrderDetailVo welfareOrderGoodsDetailVo = mapper.selectOrderDetailByOrderId(orderId);
        if (welfareOrderGoodsDetailVo.getOrderType() == WelfareOrderEnum.ORDER_TYPE_EXCHANGE.getCode() && EmptyUtils.isNotEmpty(welfareOrderGoodsDetailVo.getExchangeSecretId())) {
            WelfareExchangeSecret welfareExchangeSecret = welfareExchangeSecretService.selectByPrimaryKey(welfareOrderGoodsDetailVo.getExchangeSecretId());
            welfareOrderGoodsDetailVo.setExchangeSecretNumber(welfareExchangeSecret.getNumber());
            /*String exchangeMealIds = welfareOrderGoodsDetailVo.getExchangeMealIds();
            if (EmptyUtils.isNotEmpty(exchangeMealIds)) {
                //如果兑换券ids有值，则查询出兑换券ids对应的兑换券名称
                int[] arr = Arrays.stream(exchangeMealIds.split(",")).mapToInt(Integer::parseInt).toArray();
                List<Integer> idsList = Arrays.stream(arr).boxed().collect(Collectors.toList());
                List<WelfareExchangeMeal> welfareExchangeMealList = welfareExchangeMealService.selectByIds(idsList);
                String mealNames = StringUtils.join(welfareExchangeMealList.stream().map(WelfareExchangeMeal::getMealName).collect(Collectors.toList()));
                welfareOrderGoodsDetailVo.setExchangeMeals(mealNames);
            }*/
        }
        Integer totalGoodsQuantity = 0;
        //查询订单商品详情
        List<WelfareOrderGoodsVo> orderGoodsVoList = welfareOrderGoodsService.selectOrderGoodsVoByOrderId(orderId);
        if(EmptyUtils.isNotEmpty(orderGoodsVoList)){
            for (WelfareOrderGoodsVo welfareOrderGoodsVo:orderGoodsVoList) {
                welfareOrderGoodsVo.setCardNo("");
                welfareOrderGoodsVo.setBatchNumber("");
                totalGoodsQuantity += welfareOrderGoodsVo.getGoodsQuantity();
                if(EmptyUtils.isNotEmpty(welfareOrderGoodsVo.getCardSecretId())){
                    //如果是卡支付
                    WelfareUserCardSecretVo welfareCardSecret = welfareCardSecretService.getUserCardBindInfo(welfareOrderGoodsVo.getCardSecretId());
                    if(EmptyUtils.isNotEmpty(welfareCardSecret)){
                        welfareOrderGoodsVo.setBatchNumber(welfareCardSecret.getCardBatchNumber());
                        welfareOrderGoodsVo.setCardNo(welfareCardSecret.getNumber());
                    }
                }
                // 拼接商品信息
                StringBuilder goodsDetail = new StringBuilder();
                if (EmptyUtils.isNotEmpty(welfareOrderGoodsVo.getFirstDetailName())) {
                    goodsDetail.append(welfareOrderGoodsVo.getFirstDetailName());
                }
                if (EmptyUtils.isNotEmpty(welfareOrderGoodsVo.getSecondDetailName())) {
                    goodsDetail.append("/");
                    goodsDetail.append(welfareOrderGoodsVo.getSecondDetailName());
                }
                if (EmptyUtils.isNotEmpty(welfareOrderGoodsVo.getThirdDetailName())) {
                    goodsDetail.append("/");
                    goodsDetail.append(welfareOrderGoodsVo.getThirdDetailName());
                }
                welfareOrderGoodsVo.setGoodsDetails(goodsDetail.toString());
            };
        }
        welfareOrderGoodsDetailVo.setOrderGoodsList(orderGoodsVoList);
        welfareOrderGoodsDetailVo.setTotalGoodsQuantity(totalGoodsQuantity);
        //查询物流信息
        WelfareOrderExpress expressQuery = new WelfareOrderExpress();
        expressQuery.setOrderId(orderId);
        expressQuery.setStatus(1);
        List<WelfareOrderExpress> welfareOrderExpressList = welfareOrderExpressService.select(expressQuery);
        if (EmptyUtils.isNotEmpty(welfareOrderExpressList)) {
            welfareOrderGoodsDetailVo.setDeliveryCount(welfareOrderExpressList.size());
        }
        welfareOrderGoodsDetailVo.setWelfareOrderExpressList(welfareOrderExpressList);
        //查询订单地址
        if (EmptyUtils.isNotEmpty(welfareOrderGoodsDetailVo.getAddressId())) {
            WelfareOrderAddress welfareOrderAddressSelect = new WelfareOrderAddress();
            welfareOrderAddressSelect.setId(welfareOrderGoodsDetailVo.getAddressId());
            WelfareOrderAddress welfareOrderAddressRes = welfareOrderAddressService.selectOne(welfareOrderAddressSelect);
            if (EmptyUtils.isNotEmpty(welfareOrderAddressRes)) {
                welfareOrderGoodsDetailVo.setOrderAddress(welfareOrderAddressRes);
            }
        }
        if(dataPort == CommonConstants.DATA_PORT.APPLET){//小程序端的判断
            if (EmptyUtils.isNotEmpty(welfareOrderGoodsDetailVo.getOrderStatus()) && welfareOrderGoodsDetailVo.getOrderStatus().equals(WelfareOrderEnum.ORDER_STATUS_DELIVERY_REFUND.getCode())) {
                welfareOrderGoodsDetailVo.setOrderStatus(WelfareOrderEnum.ORDER_STATUS_NO_DELIVERY_REFUND.getCode());
            }
            if (EmptyUtils.isNotEmpty(welfareOrderGoodsDetailVo.getOrderStatus()) && welfareOrderGoodsDetailVo.getOrderStatus().equals(WelfareOrderEnum.ORDER_STATUS_PRE_PAID.getCode())) {
                welfareOrderGoodsDetailVo.setOrderStatus(WelfareOrderEnum.ORDER_STATUS_PAID.getCode());
            }
        }else if(dataPort == CommonConstants.DATA_PORT.COMPANY){//企业端
            if (EmptyUtils.isNotEmpty(welfareOrderGoodsDetailVo.getOrderStatus()) && welfareOrderGoodsDetailVo.getOrderStatus().equals(WelfareOrderEnum.ORDER_STATUS_PRE_PAID.getCode())) {
                welfareOrderGoodsDetailVo.setOrderStatus(WelfareOrderEnum.ORDER_STATUS_PAID.getCode());
            }
        }
        // 券密
        if (welfareOrderGoodsDetailVo.getOrderType().equals(WelfareOrderEnum.ORDER_TYPE_VIRTUAL.getCode())) {
            // 虚拟商品订单只会存在一条
            // 存在待付款状态未分配券密
            if (EmptyUtils.isNotEmpty(orderGoodsVoList.get(0).getSecretIds())) {
                String secretIds = orderGoodsVoList.get(0).getSecretIds();
                List<Integer> idList = new ArrayList<>();
                String[] secretIdsArray = secretIds.split(",");
                for (String idStr : secretIdsArray) {
                    idList.add(Integer.parseInt(idStr));
                }
                List<WelfareVoucherSecret> voucherSecretList = welfareVoucherSecretService.getVoucherSecretListByIds(idList);
                if (EmptyUtils.isNotEmpty(voucherSecretList)) {
                    welfareOrderGoodsDetailVo.setVoucherSecretList(voucherSecretList);
                }
            }
        }
        if (welfareOrderGoodsDetailVo.getOrderType().equals(WelfareOrderEnum.ORDER_TYPE_VIRTUAL_API_RECHARGE.getCode()) && welfareOrderGoodsDetailVo.getApiType().equals(WelfareOrderEnum.ORDER_API_TYPE_EXTRACT_CARD.getCode())){
            WelfareOrderApiCard welfareOrderApiCardSelect = new WelfareOrderApiCard();
            welfareOrderApiCardSelect.setOrderId(orderId);
            List<WelfareOrderApiCard> list = welfareOrderApiCardService.select(welfareOrderApiCardSelect);
            if (EmptyUtils.isNotEmpty(list)){
                welfareOrderGoodsDetailVo.setOrderApiCardList(list);
            }
        }
        return welfareOrderGoodsDetailVo;
    }

    @Master
    @Override
    public Map<String, Object> addUserOrder(WelfareOrderDto welfareOrderDto) {
        Map<String, Object> resMap = new HashMap<>();
        if (EmptyUtils.isEmpty(welfareOrderDto.getOrderWay())) {
            resMap.put("code", 1801);
            resMap.put("msg", "无效的下单方式");
            return resMap;
        }
        if (welfareOrderDto.getOrderType() == null) {
            resMap.put("code", 1800);
            resMap.put("msg", "无效的操作类型");
            return resMap;
        }
        if (welfareOrderDto.getOrderType().equals(WelfareOrderEnum.ORDER_TYPE_PHYSICAL.getCode())) {
            resMap = orderAddPhysicalService.addOrder(welfareOrderDto);
        } else if (welfareOrderDto.getOrderType().equals(WelfareOrderEnum.ORDER_TYPE_EXCHANGE.getCode())) {
            resMap = orderAddExchangeService.addOrder(welfareOrderDto);
        } else if (welfareOrderDto.getOrderType().equals(WelfareOrderEnum.ORDER_TYPE_VIRTUAL.getCode())) {
            resMap = orderAddVirtualService.addOrder(welfareOrderDto);
        } else if (welfareOrderDto.getOrderType().equals(WelfareOrderEnum.ORDER_TYPE_VIRTUAL_API_RECHARGE.getCode())) {
            WelfareOrderGoodsDto welfareOrderGoodsDto = welfareOrderDto.getOrderGoodsList().get(0);
            if(EmptyUtils.isNotEmpty(welfareOrderGoodsDto.getSupplierId())){
                WelfareSupplier welfareSupplier = welfareSupplierService.selectByPrimaryKey(welfareOrderGoodsDto.getSupplierId());
                if (welfareSupplier.getMerchantId().equals(ApiExtractCardConstant.getMerchantId())){
                    resMap = orderAddApiExtractCardService.addOrder(welfareOrderDto);
                } else {
                    resMap = orderAddApiRechargeService.addOrder(welfareOrderDto);
                }
            }else{
                WelfareGoods welfareGoods = welfareGoodsService.selectByPrimaryKey(welfareOrderGoodsDto.getGoodsId());
                WelfareSupplier welfareSupplier = welfareSupplierService.selectByPrimaryKey(welfareGoods.getSupplierId());
                if (welfareSupplier.getMerchantId().equals(ApiExtractCardConstant.getMerchantId())){
                    resMap = orderAddApiExtractCardService.addOrder(welfareOrderDto);
                } else {
                    resMap = orderAddApiRechargeService.addOrder(welfareOrderDto);
                }
            }
        } else {
            resMap.put("code", 1800);
            resMap.put("msg", "无效的下单类型");
            return resMap;
        }
        return resMap;
    }

    @Override
    public Map<String, Object> updateExchangeOrderAndSplit(WelfareOrderExchangeDto welfareOrderExchangeDto) {
        Map<String, Object> resMap = new HashMap<>();
        WelfareOrder welfareOrderRes = mapper.selectByPrimaryKey(welfareOrderExchangeDto.getOrderId());
        if (EmptyUtils.isEmpty(welfareOrderRes)) {
            throw new CommonException("无效的订单");
        }
        if (EmptyUtils.isNotEmpty(welfareOrderRes.getOrderType()) && !welfareOrderRes.getOrderType().equals(WelfareOrderEnum.ORDER_TYPE_EXCHANGE.getCode())) {
            throw new CommonException("无效的订单类型");
        }
        WelfareExchangeSecret welfareExchangeSecretRes = welfareExchangeSecretService.selectByPrimaryKey(welfareOrderExchangeDto.getExchangeSecretId());
        if (!(EmptyUtils.isNotEmpty(welfareExchangeSecretRes) && EmptyUtils.isEmpty(welfareExchangeSecretRes.getUsedTime()) && welfareExchangeSecretRes.getStatus()==CommonConstants.YES
           && (welfareExchangeSecretRes.getIsActivate()==WelfareExchangeEnum.EXCHANGE_SECRET_ACTIVE_STATUS_ACTIVATED.getCode() || welfareExchangeSecretRes.getIsActivate()==WelfareExchangeEnum.EXCHANGE_SECRET_ACTIVE_STATUS_BOUND.getCode()))) {
            throw new CommonException("无效的兑换券信息");
        }
        // 释放预占
        updateReleaseLockAndSubQuantity(welfareOrderExchangeDto.getOrderId());
        // 设置订单状态和兑换券信息
        welfareOrderRes.setStatus(1);
        welfareOrderRes.setExchangeSecretId(welfareOrderExchangeDto.getExchangeSecretId());
        // 获取订单商品列表
        Example welfareOrderGoodsExample = new Example(WelfareOrderGoods.class);
        welfareOrderGoodsExample.createCriteria().andEqualTo("orderId", welfareOrderExchangeDto.getOrderId());
        List<WelfareOrderGoods> welfareOrderGoodsListRes = welfareOrderGoodsService.selectByExample(welfareOrderGoodsExample);
        // 拆单
        updateOrderSplitBySupplier(welfareOrderRes, welfareOrderGoodsListRes);
        // 核销兑换券
        WelfareExchangeSecret welfareExchangeSecretUpd = new WelfareExchangeSecret();
        welfareExchangeSecretUpd.setId(welfareOrderExchangeDto.getExchangeSecretId());
        //welfareExchangeSecretUpd.setIsUsed(1);
        welfareExchangeSecretUpd.setUsedTime(new Date());
        welfareExchangeSecretUpd.setIsActivate(WelfareExchangeEnum.EXCHANGE_SECRET_ACTIVE_STATUS_USED.getCode());
        welfareExchangeSecretService.updateByPrimaryKeySelective(welfareExchangeSecretUpd);
        resMap.put("code", 1);
        resMap.put("orderId", welfareOrderExchangeDto.getOrderId());
        resMap.put("msg", "success");
        return resMap;
    }

    /**
     * 以卡密id为key，将匹配到的商品放到放到商品列表的HashMap中
     * @param map                     map对象
     * @param cardSecretId            卡密id
     * @param welfareOrderGoodsCardVo 订单商品对象
     * @return void
     * @author ChenLong
     * @date 2021-05-25 20:28:45
     **/
    private void putOrderGoodsAddCard(Map<Integer, List<WelfareOrderGoodsCardVo>> map, Integer cardSecretId, WelfareOrderGoodsCardVo welfareOrderGoodsCardVo) {
        List<WelfareOrderGoodsCardVo> orderGoodsVoList;
        if (map.containsKey(cardSecretId)) {
            orderGoodsVoList = map.get(cardSecretId);
            orderGoodsVoList.add(welfareOrderGoodsCardVo);
        } else {
            orderGoodsVoList = new ArrayList<>();
            orderGoodsVoList.add(welfareOrderGoodsCardVo);
        }
        map.put(cardSecretId, orderGoodsVoList);
    }

    /**
     * 订单商品需支付积分总数求和（乘以了数量）
     * @param welfareOrderGoodsList 订单商品列表
     * @return java.math.BigDecimal
     * @author ChenLong
     * @date 2021-05-25 20:27:15
     **/
    private BigDecimal sumOrderGoodsCredits(List<WelfareOrderGoodsCardVo> welfareOrderGoodsList) {
        log.info("sumOrderGoodsCredits welfareOrderGoodsList: " + welfareOrderGoodsList.toString());
        return welfareOrderGoodsList.stream().map(s -> s.getCreditsAmount().multiply(BigDecimal.valueOf(s.getGoodsQuantity()))).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    /**
     * 计算卡需支付总和
     * @param welfareOrderGoodsCardVo 商品卡对象
     * @param welfareUserCardSecretVo 卡列表
     * @return void
     * @author ChenLong
     * @date 2021-06-23 20:22:31
     **/
    private void sumCardSecretTotalAmount(WelfareOrderGoodsCardVo welfareOrderGoodsCardVo, WelfareUserCardSecretVo welfareUserCardSecretVo) {
        // 卡内余额
        BigDecimal remainAmount = welfareUserCardSecretVo.getRemainAmount();
        // 本条商品价格总和
        BigDecimal goodsAmount = welfareOrderGoodsCardVo.getCreditsAmount().multiply(BigDecimal.valueOf(welfareOrderGoodsCardVo.getGoodsQuantity()));
        welfareOrderGoodsCardVo.setPaymentTotal(goodsAmount);
        // 当前需支付积分总和
        if (EmptyUtils.isEmpty(welfareUserCardSecretVo.getTotalPaymentAmount())) {
            welfareUserCardSecretVo.setTotalPaymentAmount(goodsAmount);
        } else {
            welfareUserCardSecretVo.setTotalPaymentAmount(welfareUserCardSecretVo.getTotalPaymentAmount().add(goodsAmount));
        }
        // 如果剩余积分够
        if (remainAmount.compareTo(welfareUserCardSecretVo.getTotalPaymentAmount()) > 0) {
            // 卡支付信息
            welfareUserCardSecretVo.setTotalCreditsAmount(welfareUserCardSecretVo.getTotalPaymentAmount());
            welfareUserCardSecretVo.setTotalCashAmount(BigDecimal.ZERO);
        } else {
            // 如果积分不够
            // 卡支付信息
            welfareUserCardSecretVo.setTotalCreditsAmount(remainAmount);
            BigDecimal totalCashAmount = welfareUserCardSecretVo.getTotalPaymentAmount().subtract(remainAmount);
            welfareUserCardSecretVo.setTotalCashAmount(totalCashAmount);
        }
    }

    /**
     * 计算支付总和（根据卡）
     * @param welfareCardSecretListUseful 卡列表
     * @param welfareOrderGoodsPayVo      支付信息对象
     * @return void
     * @author ChenLong
     * @date 2021-06-23 20:22:31
     **/
    private void sumTotalAmountByCard(List<WelfareUserCardSecretVo> welfareCardSecretListUseful, WelfareOrderGoodsPayVo welfareOrderGoodsPayVo) {
        log.info("sumTotalAmountByCard welfareCardSecretListUseful: " + welfareCardSecretListUseful.toString());
        log.info("sumTotalAmountByCard welfareOrderGoodsPayVo: " + welfareOrderGoodsPayVo.toString());
        for (WelfareUserCardSecretVo welfareUserCardSecretVo : welfareCardSecretListUseful) {
            if (EmptyUtils.isNotEmpty(welfareUserCardSecretVo.getTotalCreditsAmount())) {
                if (EmptyUtils.isNotEmpty(welfareOrderGoodsPayVo.getTotalPayCreditsAmount())) {
                    welfareOrderGoodsPayVo.setTotalPayCreditsAmount(welfareUserCardSecretVo.getTotalCreditsAmount().add(welfareOrderGoodsPayVo.getTotalPayCreditsAmount()));
                } else {
                    welfareOrderGoodsPayVo.setTotalPayCreditsAmount(welfareUserCardSecretVo.getTotalCreditsAmount());
                }
            }
            if (EmptyUtils.isNotEmpty(welfareUserCardSecretVo.getTotalCashAmount())) {
                if (EmptyUtils.isNotEmpty(welfareOrderGoodsPayVo.getTotalPayCashAmount())) {
                    welfareOrderGoodsPayVo.setTotalPayCashAmount(welfareUserCardSecretVo.getTotalCashAmount().add(welfareOrderGoodsPayVo.getTotalPayCashAmount()));
                } else {
                    welfareOrderGoodsPayVo.setTotalPayCashAmount(welfareUserCardSecretVo.getTotalCashAmount());
                }
            }
            if (EmptyUtils.isNotEmpty(welfareUserCardSecretVo.getTotalPaymentAmount())) {
                if (EmptyUtils.isNotEmpty(welfareOrderGoodsPayVo.getTotalPayAmount())) {
                    welfareOrderGoodsPayVo.setTotalPayAmount(welfareUserCardSecretVo.getTotalPaymentAmount().add(welfareOrderGoodsPayVo.getTotalPayAmount()));
                } else {
                    welfareOrderGoodsPayVo.setTotalPayAmount(welfareUserCardSecretVo.getTotalPaymentAmount());
                }
            }
        }
    }

    @Override
    public Map<String, Object> addOrderGoodsPayMatchByOrderId(Integer userId, Integer orderId) {
        Map<String, Object> resMap = new HashMap<>();
        // 获取订单商品列表
        List<WelfareOrderGoodsCardVo> orderGoodsVoList = welfareOrderGoodsService.getOrderGoodsByOrderId(orderId);
        if (EmptyUtils.isEmpty(orderGoodsVoList)) {
            resMap.put("code", 1001);
            resMap.put("msg", "无效的商品信息");
            return resMap;
        }
        // 获取用户可用卡列表
        List<WelfareUserCardSecretVo> welfareCardSecretList = welfareCardSecretService.getUserCardBindListForOrderPay(userId);
        // 以卡密id为key，将匹配到的商品放到放到商品列表的HashMap中
        Map<Integer, List<WelfareOrderGoodsCardVo>> map = new HashMap<>();
        welfareCardSecretList = welfareCardSecretList.stream().sorted(Comparator.comparing(WelfareUserCardSecretVo::getRemainAmount).reversed()).collect(Collectors.toList());// 按照剩余额额度排序
        List<WelfareUserCardSecretVo> welfareCardSecretCommonList = welfareCardSecretList.stream().filter(s -> s.getCardPartitionIds().contains(0)).collect(Collectors.toList());// 通兑卡列表
        // 组装匹配结果，并计算支付总额和待补差金额
        WelfareOrderGoodsPayVo welfareOrderGoodsPayVo = new WelfareOrderGoodsPayVo();
        welfareOrderGoodsPayVo.setTotalPayCreditsAmount(BigDecimal.ZERO);
        welfareOrderGoodsPayVo.setTotalPayCashAmount(BigDecimal.ZERO);
        // 可匹配到商品的卡Map，以卡id为key
        Map<Integer, WelfareUserCardSecretVo> cardSecretVoMap = new HashMap<>();
        int matchCardFlag;
        List<WelfareOrderGoodsCardVo> orderGoodsVoMatchedList = new ArrayList<>();
        // 从商品纬度匹配卡（如果这个商品能匹配到卡直接匹配到该卡，如果匹配不到卡。则判断是否包含通兑卡，包含通兑卡：未匹配到卡的归类到通兑卡，不包含通兑卡：未匹配到卡的归类到未匹配列表）
        for (WelfareOrderGoodsCardVo welfareOrderGoodsCardVo : orderGoodsVoList) {
            matchCardFlag = 0;
            // 优先匹配到对应卡类型
            for (WelfareUserCardSecretVo welfareUserCardSecretVo : welfareCardSecretList) {
                // 卡和分区匹配
                if (welfareUserCardSecretVo.getCardPartitionIds().contains(welfareOrderGoodsCardVo.getPartitionId())) {
                    // 该分区已经匹配到卡了，将该卡加入到可用卡列表
                    if (matchCardFlag > 0) {
                        if (!cardSecretVoMap.containsKey(welfareUserCardSecretVo.getId())) {
                            cardSecretVoMap.put(welfareUserCardSecretVo.getId(), welfareUserCardSecretVo);
                        }
                    } else {
                        // 修改为已经匹配到的flag
                        matchCardFlag = 1;
                        welfareOrderGoodsCardVo.setCardSecretId(welfareUserCardSecretVo.getId());
                        // 累加该卡需支付的积分、补差及总额
                        sumCardSecretTotalAmount(welfareOrderGoodsCardVo, welfareUserCardSecretVo);
                        if (!cardSecretVoMap.containsKey(welfareUserCardSecretVo.getId())) {
                            cardSecretVoMap.put(welfareUserCardSecretVo.getId(), welfareUserCardSecretVo);
                        }
                        orderGoodsVoMatchedList.add(welfareOrderGoodsCardVo);// 加入到匹配列表
                    }
                }
            }
            // 如果循环完，商品依然匹配不到卡
            // 如果包含通兑卡,匹配不到卡的都放到通兑卡
            if (EmptyUtils.isNotEmpty(welfareCardSecretCommonList) && welfareCardSecretCommonList.size() > 0) {
                for (WelfareUserCardSecretVo welfareUserCardSecretVoTemp : welfareCardSecretCommonList) {
                    if (welfareUserCardSecretVoTemp.getCardPartitionIds().contains(0)) {
                        if (matchCardFlag > 0) {
                            cardSecretVoMap.put(welfareUserCardSecretVoTemp.getId(), welfareUserCardSecretVoTemp);
                        } else {
                            // 修改为已经匹配到的flag
                            matchCardFlag = 1;
                            welfareOrderGoodsCardVo.setCardSecretId(welfareUserCardSecretVoTemp.getId());
                            // 累加该卡需支付的积分、补差及总额
                            sumCardSecretTotalAmount(welfareOrderGoodsCardVo, welfareUserCardSecretVoTemp);
                            cardSecretVoMap.put(welfareUserCardSecretVoTemp.getId(), welfareUserCardSecretVoTemp);
                            orderGoodsVoMatchedList.add(welfareOrderGoodsCardVo);// 加入到匹配列表
                        }
                    }
                }
            } else {
                // 如果没有匹配到对应类型卡也没有匹配到通兑卡
                if (matchCardFlag == 0) {
                    putOrderGoodsAddCard(map, -1, welfareOrderGoodsCardVo);
                }
            }
        }
        // 如果有未匹配到卡的记录
        if (map.containsKey(-1)) {
            List<WelfareOrderGoodsCardVo> welfareOrderGoodsList = map.get(-1);
            // 求和,得到需支付现金总额（此处也是补差总额）
            BigDecimal totalCashAmount = sumOrderGoodsCredits(welfareOrderGoodsList);
            WelfareOrderGoodsPayUnMatchVo unMatchedGoodsListInfo = new WelfareOrderGoodsPayUnMatchVo();
            unMatchedGoodsListInfo.setTotalCashAmount(totalCashAmount);
            unMatchedGoodsListInfo.setOrderGoodsVoList(welfareOrderGoodsList);
            welfareOrderGoodsPayVo.setUnMatchedGoodsListInfo(unMatchedGoodsListInfo);
            // 计算总支付积分、补差
            welfareOrderGoodsPayVo.setTotalPayCashAmount(welfareOrderGoodsPayVo.getTotalPayCashAmount().add(totalCashAmount));
        }
        // 可用卡列表
        List<WelfareUserCardSecretVo> welfareCardSecretListUseful = new ArrayList<>();
        for (Map.Entry<Integer, WelfareUserCardSecretVo> entry : cardSecretVoMap.entrySet()) {
            welfareCardSecretListUseful.add(entry.getValue());
        }
        // 计算支付总和（根据卡列表）
        sumTotalAmountByCard(welfareCardSecretListUseful, welfareOrderGoodsPayVo);
        welfareOrderGoodsPayVo.setOrderId(orderId);
        welfareOrderGoodsPayVo.setUserId(userId);
        welfareOrderGoodsPayVo.setOrderGoodsVoList(orderGoodsVoMatchedList);
        welfareOrderGoodsPayVo.setUsefulCardSecretList(welfareCardSecretListUseful);
        welfareOrderGoodsPayVo.setTotalPayAmount(welfareOrderGoodsPayVo.getTotalPayCreditsAmount().add(welfareOrderGoodsPayVo.getTotalPayCashAmount()));
        resMap.put("code", 1);
        resMap.put("msg", "success");
        resMap.put("data", welfareOrderGoodsPayVo);
        return resMap;
    }

    @Override
    public WelfareOrderGoodsPayVo addOrderGoodsPayMatchReDefine(Integer userId, WelfareOrderGoodsPayMatchDto welfareOrderGoodsPayMatchDto) {
        Integer orderId = welfareOrderGoodsPayMatchDto.getOrderId();
        // 获取用户的卡列表，以id为key放到HashMap中
        List<WelfareUserCardSecretVo> welfareCardSecretList = welfareCardSecretService.getUserCardBindListForOrderPay(userId);
        welfareCardSecretList = welfareCardSecretList.stream().sorted(Comparator.comparing(WelfareUserCardSecretVo::getRemainAmount)).collect(Collectors.toList());// 按照剩余额额度排序
        log.info("addOrderGoodsPayMatchReDefine welfareCardSecretList: " + welfareCardSecretList.toString());
        // 获取订单商品列表，以orderId、goodsId、skuId为key放入到Map中
        List<WelfareOrderGoodsCardVo> orderGoodsVoList = welfareOrderGoodsService.getOrderGoodsByOrderId(orderId);
        Map<String, WelfareOrderGoodsCardVo> orderGoodsCardMap = new HashMap<>();
        for (WelfareOrderGoodsCardVo welfareOrderGoodsCardVo : orderGoodsVoList) {
            String key = welfareOrderGoodsCardVo.getOrderId().toString() + welfareOrderGoodsCardVo.getGoodsId().toString() + welfareOrderGoodsCardVo.getSkuId().toString();
            orderGoodsCardMap.put(key, welfareOrderGoodsCardVo);
        }
        return addOrderGoodsPayMatch(userId, welfareOrderGoodsPayMatchDto, orderGoodsCardMap, welfareCardSecretList);
    }

    /**
     * 订单商品支付匹配
     * @param userId                       用户id
     * @param welfareOrderGoodsPayMatchDto 订单商品实体
     * @param orderGoodsCardMap            订单商品Map
     * @param welfareCardSecretList        卡密列表
     * @return com.dzl.order.pojo.vo.WelfareOrderGoodsPayVo
     * @author ChenLong
     * @date 2021-06-16 10:30:22
     **/
    private WelfareOrderGoodsPayVo addOrderGoodsPayMatch(Integer userId, WelfareOrderGoodsPayMatchDto welfareOrderGoodsPayMatchDto, Map<String, WelfareOrderGoodsCardVo> orderGoodsCardMap, List<WelfareUserCardSecretVo> welfareCardSecretList) {
        log.info("addOrderGoodsPayMatch orderGoodsCardMap: " + orderGoodsCardMap.toString());
        Integer orderId = welfareOrderGoodsPayMatchDto.getOrderId();
        WelfareOrderGoodsPayVo welfareOrderGoodsPayVo = new WelfareOrderGoodsPayVo();
        welfareOrderGoodsPayVo.setTotalPayCreditsAmount(BigDecimal.ZERO);
        welfareOrderGoodsPayVo.setTotalPayCashAmount(BigDecimal.ZERO);
        // 未匹配到卡的商品列表补差支付
        List<WelfareOrderPayMatchGoodsDto> unMatchedGoodsList = welfareOrderGoodsPayMatchDto.getUnMatchedGoodsList();
        if (EmptyUtils.isNotEmpty(unMatchedGoodsList)) {
            // 未匹配到卡的订单商品列表
            List<WelfareOrderGoodsCardVo> unMatchOrderGoodsVoList = new ArrayList<>();
            BigDecimal totalCashAmount = addGoodsTotalAmountAndBuildGoodsList(unMatchedGoodsList, orderGoodsCardMap, unMatchOrderGoodsVoList);
            // 计算总支付积分、补差
            welfareOrderGoodsPayVo.setTotalPayCashAmount(welfareOrderGoodsPayVo.getTotalPayCashAmount().add(totalCashAmount));
            WelfareOrderGoodsPayUnMatchVo welfareOrderPayUnMatchGoodsVo = new WelfareOrderGoodsPayUnMatchVo();
            welfareOrderPayUnMatchGoodsVo.setOrderGoodsVoList(unMatchOrderGoodsVoList);
            welfareOrderPayUnMatchGoodsVo.setTotalCashAmount(totalCashAmount);
            welfareOrderGoodsPayVo.setUnMatchedGoodsListInfo(welfareOrderPayUnMatchGoodsVo);
        }
        // 可匹配到商品的卡Map，以卡id为key
        Map<Integer, WelfareUserCardSecretVo> cardSecretVoMap = new HashMap<>();
        List<WelfareOrderGoodsCardVo> welfareOrderGoodsCardVoList = new ArrayList<>();
        // 匹配到卡的商品
        List<WelfareOrderGoodsPayMatchGoodsDto> cardGoodsList = welfareOrderGoodsPayMatchDto.getCardGoodsList();
        if (EmptyUtils.isNotEmpty(cardGoodsList) && cardGoodsList.size() > 0) {
            for (WelfareOrderGoodsPayMatchGoodsDto orderGoodsPayMatchGoodsListDto : cardGoodsList) {
                // 获取本条匹配记录的商品信息（数据库）
                String orderIdKey = orderId.toString();
                String goodsIdKey = orderGoodsPayMatchGoodsListDto.getGoodsId().toString();
                String skuIdKey = orderGoodsPayMatchGoodsListDto.getSkuId().toString();
                String orderGoodsKey = orderIdKey + goodsIdKey + skuIdKey;
                WelfareOrderGoodsCardVo welfareOrderGoodsCardVoTemp = orderGoodsCardMap.get(orderGoodsKey);
                welfareOrderGoodsCardVoTemp.setCardSecretId(orderGoodsPayMatchGoodsListDto.getCardSecretId());
                welfareOrderGoodsCardVoList.add(welfareOrderGoodsCardVoTemp);
                // 匹配可用卡，计算卡支付信息
                for (WelfareUserCardSecretVo welfareUserCardSecretVo : welfareCardSecretList) {
                    // 卡和商品分区能对上，加入到可用卡列表
                    if (welfareUserCardSecretVo.getCardPartitionIds().contains(welfareOrderGoodsCardVoTemp.getPartitionId())) {
                        // 商品匹配到卡了，将该卡加入到可用卡列表
                        if (welfareUserCardSecretVo.getId().equals(orderGoodsPayMatchGoodsListDto.getCardSecretId())) {
                            // 累加该卡需支付的积分、补差及总额
                            sumCardSecretTotalAmount(welfareOrderGoodsCardVoTemp, welfareUserCardSecretVo);
                            if (!cardSecretVoMap.containsKey(welfareUserCardSecretVo.getId())) {
                                cardSecretVoMap.put(welfareUserCardSecretVo.getId(), welfareUserCardSecretVo);
                            }
                        } else {
                            if (!cardSecretVoMap.containsKey(welfareUserCardSecretVo.getId())) {
                                cardSecretVoMap.put(welfareUserCardSecretVo.getId(), welfareUserCardSecretVo);
                            }
                        }
                    }
                    // 通兑卡都加入到可用卡列表
                    if (welfareUserCardSecretVo.getCardPartitionIds().contains(0)) {
                        // 商品匹配到卡了，将该卡加入到可用卡列表
                        if (welfareUserCardSecretVo.getId().equals(orderGoodsPayMatchGoodsListDto.getCardSecretId())) {
                            // 累加该卡需支付的积分、补差及总额
                            sumCardSecretTotalAmount(welfareOrderGoodsCardVoTemp, welfareUserCardSecretVo);
                        }
                        if (!cardSecretVoMap.containsKey(welfareUserCardSecretVo.getId())) {
                            cardSecretVoMap.put(welfareUserCardSecretVo.getId(), welfareUserCardSecretVo);
                        }
                    }
                }
            }
        }
        // 可用卡列表
        List<WelfareUserCardSecretVo> welfareCardSecretListUseful = new ArrayList<>();
        for (Map.Entry<Integer, WelfareUserCardSecretVo> entry : cardSecretVoMap.entrySet()) {
            welfareCardSecretListUseful.add(entry.getValue());
        }
        // 计算支付总和（根据卡列表）
        sumTotalAmountByCard(welfareCardSecretListUseful, welfareOrderGoodsPayVo);
        // 组装返回结果
        welfareOrderGoodsPayVo.setOrderId(orderId);
        welfareOrderGoodsPayVo.setUserId(userId);
        if (EmptyUtils.isNotEmpty(welfareOrderGoodsCardVoList)) {
            welfareOrderGoodsPayVo.setOrderGoodsVoList(welfareOrderGoodsCardVoList);
        }
        welfareOrderGoodsPayVo.setUsefulCardSecretList(welfareCardSecretListUseful);
        welfareOrderGoodsPayVo.setTotalPayAmount(welfareOrderGoodsPayVo.getTotalPayCreditsAmount().add(welfareOrderGoodsPayVo.getTotalPayCashAmount()));
        return welfareOrderGoodsPayVo;
    }

    /**
     * 以供应商为纬度拆单
     * @param map                     以供应商id为key，订单商品列表为value的map
     * @param cardSecretId            供应商id
     * @param welfareOrderGoodsCardVo 订单商品列表
     * @return void
     * @author ChenLong
     * @date 2021-06-06 12:36:17
     **/
    private void putOrderGoodsAddCardSecretId(Map<Integer, List<WelfareOrderGoodsCardVo>> map, Integer cardSecretId, WelfareOrderGoodsCardVo welfareOrderGoodsCardVo) {
        List<WelfareOrderGoodsCardVo> welfareOrderGoodsDtoList;
        if (map.containsKey(cardSecretId)) {
            welfareOrderGoodsDtoList = map.get(cardSecretId);
            welfareOrderGoodsDtoList.add(welfareOrderGoodsCardVo);
        } else {
            welfareOrderGoodsDtoList = new ArrayList<>();
            welfareOrderGoodsDtoList.add(welfareOrderGoodsCardVo);
        }
        map.put(cardSecretId, welfareOrderGoodsDtoList);
    }

    /**
     * 订单商品和卡支付重新匹配（计算订单商品记录总额，并组该卡下面的商品列表）
     * @param goodsDtoList         商品列表
     * @param orderGoodsCardMap    商品Map（数据库取出来的商品信息）
     * @param orderGoodsCardVoList 订单商品出参组装
     * @return java.math.BigDecimal
     * @author ChenLong
     * @date 2021-06-11 11:01:44
     **/
    private BigDecimal addGoodsTotalAmountAndBuildGoodsList(List<WelfareOrderPayMatchGoodsDto> goodsDtoList, Map<String, WelfareOrderGoodsCardVo> orderGoodsCardMap, List<WelfareOrderGoodsCardVo> orderGoodsCardVoList) {
        BigDecimal totalCashAmount = BigDecimal.ZERO;
        for (WelfareOrderPayMatchGoodsDto welfareOrderPayMatchGoodsDto : goodsDtoList) {
            // 积分价格从数据库获取，需求数量取前台传值
            String key = welfareOrderPayMatchGoodsDto.getOrderId().toString() + welfareOrderPayMatchGoodsDto.getGoodsId().toString() + welfareOrderPayMatchGoodsDto.getSkuId().toString();
            WelfareOrderGoodsCardVo welfareOrderGoodsCard = orderGoodsCardMap.get(key);
            if (EmptyUtils.isEmpty(welfareOrderGoodsCard)) {
                throw new CommonException("无效的订单商品");
            }
            BigDecimal creditsAmount = welfareOrderGoodsCard.getCreditsAmount();
            Integer quantity = welfareOrderPayMatchGoodsDto.getQuantity();
            BigDecimal singleAmount = creditsAmount.multiply(BigDecimal.valueOf(quantity));
            totalCashAmount = totalCashAmount.add(singleAmount);
            // 组拼商品列表
            orderGoodsCardVoList.add(welfareOrderGoodsCard);
        }
        return totalCashAmount;
    }

    /**
     * 校验商品购买次数（以卡为维度）
     * @param welfareOrderGoodsCardVo 卡商品列表
     * @return boolean
     * @author ChenLong
     * @date 2021-08-04 14:33:28
     **/
    private boolean validGoodsBuyLimitByCardId(WelfareOrderGoodsCardVo welfareOrderGoodsCardVo) {
        // 商品限制购买数量从商品表获取，如果限制类型为以卡维度限制，且该商品非商家状态或隐藏，则校验不让购买
        WelfareGoods welfareGoodsRes = welfareGoodsService.selectByPrimaryKey(welfareOrderGoodsCardVo.getGoodsId());
        if (EmptyUtils.isNotEmpty(welfareGoodsRes) && EmptyUtils.isNotEmpty(welfareGoodsRes.getBuyLimitType()) && welfareGoodsRes.getBuyLimitType().equals(2)) {
            if (welfareGoodsRes.getStatus().equals(0) || !welfareGoodsRes.getGoodsStatus().equals(WelfareGoodsEnum.GOODS_STATUS_TYPE_SHELVES.getCode()) || welfareGoodsRes.getIsShow().equals(0)) {
                throw new CommonException("限制卡购买次数的商品已售罄");
            }
            if (EmptyUtils.isNotEmpty(welfareGoodsRes.getBuyLimit())) {
                Integer buyLimit = welfareGoodsRes.getBuyLimit();
                // 预购买数量
                Integer reqQuantity = welfareOrderGoodsCardVo.getGoodsQuantity();
                // 该卡已购买数量
                List<WelfareOrderGoods> orderGoodsList = welfareOrderGoodsService.getPaidOrderGoodsBySecretCardId(welfareOrderGoodsCardVo.getCardSecretId(), welfareOrderGoodsCardVo.getGoodsId());
                Integer existBuyQuantity = 0;
                if (EmptyUtils.isNotEmpty(orderGoodsList) && orderGoodsList.size() > 0) {
                    for (WelfareOrderGoods welfareOrderGoods : orderGoodsList) {
                        existBuyQuantity = existBuyQuantity + welfareOrderGoods.getGoodsQuantity();
                    }
                }
                // 如果需求购买数量超出购买限制
                if (reqQuantity + existBuyQuantity > buyLimit) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public Integer addOrderConfirmForPay(Integer userId, WelfareOrderGoodsPayMatchDto welfareOrderGoodsPayMatchDto) {
        Integer orderId = welfareOrderGoodsPayMatchDto.getOrderId();
        // 获取用户的卡列表，以id为key放到HashMap中
        List<WelfareUserCardSecretVo> welfareCardSecretList = welfareCardSecretService.getUserCardBindListForOrderPay(userId);
        welfareCardSecretList = welfareCardSecretList.stream().sorted(Comparator.comparing(WelfareUserCardSecretVo::getRemainAmount)).collect(Collectors.toList());// 按照剩余额额度排序
        // 获取订单商品列表，以orderId、goodsId、skuId为key放入到Map中
        List<WelfareOrderGoodsCardVo> orderGoodsVoList = welfareOrderGoodsService.getOrderGoodsByOrderId(orderId);
        Map<String, WelfareOrderGoodsCardVo> orderGoodsCardMap = new HashMap<>();
        for (WelfareOrderGoodsCardVo welfareOrderGoodsCardVo : orderGoodsVoList) {
            String key = welfareOrderGoodsCardVo.getOrderId().toString() + welfareOrderGoodsCardVo.getGoodsId().toString() + welfareOrderGoodsCardVo.getSkuId().toString();
            orderGoodsCardMap.put(key, welfareOrderGoodsCardVo);
        }
        // 补差
        WelfareOrderGoodsPayVo welfareOrderGoodsPayVo = addOrderGoodsPayMatch(userId, welfareOrderGoodsPayMatchDto, orderGoodsCardMap, welfareCardSecretList);
        List<WelfareOrderGoods> welfareOrderGoodsList = new ArrayList<>();
        WelfareOrderGoodsPayUnMatchVo unMatchedGoodsListInfo = welfareOrderGoodsPayVo.getUnMatchedGoodsListInfo();
        if (EmptyUtils.isNotEmpty(unMatchedGoodsListInfo)) {
            List<WelfareOrderGoodsCardVo> orderGoodsCardVoList = unMatchedGoodsListInfo.getOrderGoodsVoList();
            if (EmptyUtils.isNotEmpty(orderGoodsCardVoList)) {
                for (WelfareOrderGoodsCardVo welfareOrderGoodsCardVo : orderGoodsCardVoList) {
                    WelfareOrderGoods welfareOrderGoods = new WelfareOrderGoods();
                    // 未匹配到卡的补差金额就为商品金额
                    welfareOrderGoods.setId(welfareOrderGoodsCardVo.getId());
                    welfareOrderGoods.setPaymentAmount(welfareOrderGoodsCardVo.getCreditsAmount().multiply(BigDecimal.valueOf(welfareOrderGoodsCardVo.getGoodsQuantity())));
                    welfareOrderGoods.setPaymentCredits(BigDecimal.ZERO);
                    welfareOrderGoods.setUpdateTime(new Date());
                    welfareOrderGoodsList.add(welfareOrderGoods);
                }
            }
        }
        // 卡匹配
        List<WelfareOrderGoodsCardVo> orderGoodsCardVoList = welfareOrderGoodsPayVo.getOrderGoodsVoList();
        List<WelfareUserCardSecretVo> usefulCardSecretList = welfareOrderGoodsPayVo.getUsefulCardSecretList();
        if (EmptyUtils.isNotEmpty(orderGoodsCardVoList) && orderGoodsCardVoList.size() > 0) {
            // 将匹配到卡的商品以卡id为key、商品为值列表放入到Map中
            Map<Integer, List<WelfareOrderGoodsCardVo>> cardGoodsMap = new HashMap<>();
            for (WelfareOrderGoodsCardVo welfareOrderGoodsCardVo : orderGoodsCardVoList) {
                // 校验商品是否超出卡维度购买限制
                if (validGoodsBuyLimitByCardId(welfareOrderGoodsCardVo)) {
                    throw new CommonException("商品超出卡购买限制");
                } else {
                    putOrderGoodsAddCardSecretId(cardGoodsMap, welfareOrderGoodsCardVo.getCardSecretId(), welfareOrderGoodsCardVo);
                }
            }
            // 将可用卡列表以卡id为key，卡信息为值放入到Map中
            Map<Integer, WelfareUserCardSecretVo> usefulCardSecretMap = new HashMap<>();
            for (WelfareUserCardSecretVo welfareUserCardSecretVo : usefulCardSecretList) {
                if (!usefulCardSecretMap.containsKey(welfareUserCardSecretVo.getId())) {
                    usefulCardSecretMap.put(welfareUserCardSecretVo.getId(), welfareUserCardSecretVo);
                }
            }
            for (Map.Entry<Integer, List<WelfareOrderGoodsCardVo>> entry : cardGoodsMap.entrySet()) {
                Integer cardSecretId = entry.getKey();
                if (EmptyUtils.isEmpty(cardSecretId)) {
                    throw new CommonException("无效的卡信息");
                }
                WelfareUserCardSecretVo welfareUserCardSecretVo = usefulCardSecretMap.get(cardSecretId);
                BigDecimal cardRemainAmount = welfareUserCardSecretVo.getRemainAmount();
                List<WelfareOrderGoodsCardVo> welfareOrderGoodsCardVoList = entry.getValue();
                // 该卡下商品的积分总和（用于均摊）
                BigDecimal totalCardCreditsAmount = welfareUserCardSecretVo.getTotalPaymentAmount();
                // 该卡下商品需支付金额总和（用于均摊）
                BigDecimal totalPaymentAmount = welfareUserCardSecretVo.getTotalCashAmount();
                // 该卡下商品需支付积分总和（用于均摊）
                BigDecimal totalPaymentCredits = welfareUserCardSecretVo.getTotalCreditsAmount();
                // 当前支付
                BigDecimal tempTotalCreditsAmount = BigDecimal.ZERO;
                BigDecimal tempTotalPaymentAmount = BigDecimal.ZERO;
                // 如果列表不为空且补差金额大于0，则需要均摊
                if (EmptyUtils.isNotEmpty(welfareOrderGoodsCardVoList)) {
                    for (int i = 0; i < welfareOrderGoodsCardVoList.size(); i++) {
                        WelfareOrderGoodsCardVo welfareOrderGoodsCardVo = welfareOrderGoodsCardVoList.get(i);
                        WelfareOrderGoods welfareOrderGoods = new WelfareOrderGoods();
                        welfareOrderGoods.setId(welfareOrderGoodsCardVo.getId());
                        // 如果补差了并且商品数量大于1，则需要进行均摊
                        if (welfareOrderGoodsCardVoList.size() > 1) {
                            if (totalPaymentAmount.compareTo(MIN_SHARE_PRICE) > 0) {
                                // 最后一条商品均摊，用总额减去其他商品的和（防止计算以后存库丢失精度）
                                if (i == welfareOrderGoodsCardVoList.size() - 1) {
                                    BigDecimal paymentAmount = totalPaymentAmount.subtract(tempTotalPaymentAmount);
                                    BigDecimal paymentCredits = cardRemainAmount.subtract(tempTotalCreditsAmount);
                                    welfareOrderGoods.setPaymentAmount(paymentAmount);
                                    welfareOrderGoods.setPaymentCredits(paymentCredits);
                                } else {
                                    BigDecimal goodsTotalAmount = welfareOrderGoodsCardVo.getCreditsAmount().multiply(BigDecimal.valueOf(welfareOrderGoodsCardVo.getGoodsQuantity()));// 商品支付积分
                                    // 商品价格除以积分总价等于商品支付比率
                                    BigDecimal cel = goodsTotalAmount.divide(totalCardCreditsAmount, 6, BigDecimal.ROUND_DOWN);// 比率保留6位（保留2位会丢失精度）
                                    // 商品积分支付数量等于：商品占总积分比率乘以商品价格
                                    BigDecimal paymentCredits = cel.multiply(totalPaymentCredits);
                                    paymentCredits = paymentCredits.setScale(2, BigDecimal.ROUND_DOWN);//保留两位小数
                                    // 商品金额支付数量等于：商品占总积分比率乘以补差积分
                                    BigDecimal paymentAmount = goodsTotalAmount.subtract(paymentCredits);
                                    welfareOrderGoods.setPaymentCredits(paymentCredits);
                                    welfareOrderGoods.setPaymentAmount(paymentAmount);
                                    tempTotalCreditsAmount = tempTotalCreditsAmount.add(paymentCredits);
                                    tempTotalPaymentAmount = tempTotalPaymentAmount.add(paymentAmount);
                                }
                            }
                            // 小于最小均摊阀值大于0
                            else if (totalPaymentAmount.compareTo(MIN_SHARE_PRICE) < 0 && MIN_SHARE_PRICE.compareTo(BigDecimal.ZERO) > 0) {
                                // 最后一条商品均摊，用总额减去其他商品的和（防止计算以后存库丢失精度）
                                if (i == welfareOrderGoodsCardVoList.size() - 1) {
                                    BigDecimal goodsTotalAmount = welfareOrderGoodsCardVo.getCreditsAmount().multiply(BigDecimal.valueOf(welfareOrderGoodsCardVo.getGoodsQuantity()));// 商品支付积分
                                    welfareOrderGoods.setPaymentAmount(totalPaymentAmount);
                                    welfareOrderGoods.setPaymentCredits(goodsTotalAmount.subtract(totalPaymentAmount));
                                } else {
                                    BigDecimal goodsTotalAmount = welfareOrderGoodsCardVo.getCreditsAmount().multiply(BigDecimal.valueOf(welfareOrderGoodsCardVo.getGoodsQuantity()));// 商品支付积分
                                    welfareOrderGoods.setPaymentAmount(BigDecimal.ZERO);
                                    welfareOrderGoods.setPaymentCredits(goodsTotalAmount);
                                    tempTotalCreditsAmount = tempTotalCreditsAmount.add(goodsTotalAmount);
                                }
                            }
                            // 未补差（无需均摊）
                            else {
                                welfareOrderGoods.setPaymentAmount(BigDecimal.ZERO);
                                // 需支付积分
                                welfareOrderGoods.setPaymentCredits(welfareOrderGoodsCardVo.getCreditsAmount().multiply(BigDecimal.valueOf(welfareOrderGoodsCardVo.getGoodsQuantity())));// 商品支付积分
                            }
                        } else {
                            //如果只有一条记录，均摊直接给到一个商品（无需均摊）
                            welfareOrderGoods.setPaymentAmount(totalPaymentAmount);
                            welfareOrderGoods.setPaymentCredits(totalPaymentCredits);
                        }
                        welfareOrderGoods.setCardSecretId(cardSecretId);//均摊卡密id
                        welfareOrderGoods.setUpdateTime(new Date());
                        welfareOrderGoodsList.add(welfareOrderGoods);
                    }
                }
            }
        }
        // 更新订单商品表里面的均摊信息
        for (WelfareOrderGoods welfareOrderGoods : welfareOrderGoodsList) {
            welfareOrderGoodsService.updateByPrimaryKeySelective(welfareOrderGoods);
        }
        // 更新订单头信息
        WelfareOrder welfareOrder = new WelfareOrder();
        welfareOrder.setId(welfareOrderGoodsPayVo.getOrderId());
        welfareOrder.setUserId(welfareOrderGoodsPayVo.getUserId());
        welfareOrder.setCreditsAmount(welfareOrderGoodsPayVo.getTotalPayCreditsAmount());
        welfareOrder.setPaymentAmount(welfareOrderGoodsPayVo.getTotalPayCashAmount());
        welfareOrder.setTotalAmount(welfareOrderGoodsPayVo.getTotalPayCreditsAmount().add(welfareOrderGoodsPayVo.getTotalPayCashAmount()));
        welfareOrder.setUpdateTime(new Date());
        welfareOrder.setOutTradeNo(StringUtil.getBillNumber());
        mapper.updateByPrimaryKeySelective(welfareOrder);
        return 1;
    }

    @Override
    public void sendMessageForPayByOrder(WelfareOrder welfareOrder) {
        log.info("sendMessageForPayByOrder: " + welfareOrder.toString());
        if (welfareOrder.getEnterpriseId().equals(CommonConstants.DEFAULT_PLATFORM_ENTERPRISE_ID)) {
            WelfareUserWx welfareUserWxRes = welfareUserWxService.selectByPrimaryKey(welfareOrder.getUserId());
            if (EmptyUtils.isNotEmpty(welfareUserWxRes)) {
                // 虚拟订单不存在拆单
                if (welfareOrder.getOrderType().equals(WelfareOrderEnum.ORDER_TYPE_VIRTUAL.getCode())) {
                    WelfareOrderGoods welfareOrderGoodsSelect = new WelfareOrderGoods();
                    welfareOrderGoodsSelect.setOrderId(welfareOrder.getId());
                    // 虚拟商品订单只会存在一条
                    WelfareOrderGoods welfareOrderGoodsRes = welfareOrderGoodsService.selectOne(welfareOrderGoodsSelect);
                    if (EmptyUtils.isNotEmpty(welfareOrderGoodsRes) && EmptyUtils.isNotEmpty(welfareOrderGoodsRes.getSecretIds())) {
                        int MAX_VOUCHER_LENGTH = 2;// 短信最多发送两条券密，剩下的用省略号
                        String secretIds = welfareOrderGoodsRes.getSecretIds();
                        List<Integer> idList = new ArrayList<>();
                        String[] secretIdsArray = secretIds.split(",");
                        for (String idStr : secretIdsArray) {
                            idList.add(Integer.parseInt(idStr));
                        }
                        List<WelfareVoucherSecret> voucherSecretList = welfareVoucherSecretService.getVoucherSecretListByIds(idList);
                        if (EmptyUtils.isNotEmpty(voucherSecretList) && voucherSecretList.size() > 0) {
                            String voucherCodeStr = "";
                            for (int i = 0; i < voucherSecretList.size(); i++) {
                                voucherCodeStr = voucherCodeStr + voucherSecretList.get(i).getSecret() + "，";
                                if (i >= MAX_VOUCHER_LENGTH - 1) {
                                    voucherCodeStr = voucherCodeStr.substring(0, voucherCodeStr.length() - 1);
                                    voucherCodeStr = voucherCodeStr + "...";
                                    break;
                                }
                            }
                            // 如果未超过指定条
                            if (MAX_VOUCHER_LENGTH - voucherSecretList.size() > 0) {
                                voucherCodeStr = voucherCodeStr.substring(0, voucherCodeStr.length() - 1);
                            }
                            SendMsgDto sendMsgDto = new SendMsgDto();
                            System.out.println("sendMessageForPayByOrder voucherCodeStr: " + voucherCodeStr);
                            sendMsgDto.setCode(voucherCodeStr);
                            sendMsgDto.setPhone(welfareUserWxRes.getPhone());
                            sendMsgDto.setType("1");
                            sendMsgDto.setGoodsName(welfareOrderGoodsRes.getGoodsName());
                            if (EmptyUtils.isNotEmpty(voucherSecretList.get(0).getExpiredTime())) {
                                DateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //HH表示24小时制；
                                String formatDate = dFormat.format(voucherSecretList.get(0).getExpiredTime());
                                System.out.println("sendMessageForPayByOrder formatDate: " + formatDate);
                                sendMsgDto.setTime(formatDate);
                            }
                            managerService.sendMsg(sendMsgDto);
                        }
                    }
                }
                // 实体订单可能存在拆单，充值订单不发短信
                else {
                    WelfareOrder welfareOrderOldIdSelect = new WelfareOrder();
                    welfareOrderOldIdSelect.setOldId(welfareOrder.getId());
                    List<WelfareOrder> welfareOrderList = mapper.select(welfareOrderOldIdSelect);
                    // 如果拆单了只有一个订单号，如果未拆单，则有多个订单号
                    if (EmptyUtils.isNotEmpty(welfareOrderList) && welfareOrderList.size() > 0) {
                        int MAX_VOUCHER_LENGTH = 2;// 短信最多发送两条订单号，剩下的用省略号
                        String orderNo = "";
                        for (int i = 0; i < welfareOrderList.size(); i++) {
                            orderNo = orderNo + welfareOrderList.get(i).getOrderNo() + "，";
                            if (i >= MAX_VOUCHER_LENGTH - 1) {
                                orderNo = orderNo.substring(0, orderNo.length() - 1);
                                orderNo = orderNo + "...";
                                break;
                            }
                        }
                        // 如果未超过指定条
                        if (MAX_VOUCHER_LENGTH - welfareOrderList.size() > 0) {
                            orderNo = orderNo.substring(0, orderNo.length() - 1);
                        }
                        SendMsgDto sendMsgDto = new SendMsgDto();
                        sendMsgDto.setPhone(welfareUserWxRes.getPhone());
                        sendMsgDto.setType("4");
                        sendMsgDto.setOrderNo(orderNo);
                        managerService.sendMsg(sendMsgDto);
                    }
                }
            }
        }
    }

    @Override
    public Map addPaymentExecute(Integer orderId, Integer type, String openId) {
        log.info("addPaymentExecute orderId: " + orderId);
        log.info("addPaymentExecute openId: " + openId);
        Map<String, Object> map = new HashMap<>();
        WelfareOrder welfareOrder = mapper.selectByPrimaryKey(orderId);
        if (EmptyUtils.isEmpty(welfareOrder.getId())) {
            map.put("code", 1001);
            map.put("msg", "无效的订单信息");
            return map;
        }
        if (!welfareOrder.getOrderStatus().equals(WelfareOrderEnum.ORDER_STATUS_UNPAY.getCode())) {
            map.put("code", 1002);
            map.put("msg", "支付失败, 请检查订单状态");
            return map;
        }
        // 支付
        if (type.equals(1)) {
            // 如果只需要积分支付，直接扣减卡余额，然后拆单
            updateOrderAndSplitForPay(welfareOrder);
            map.put("code", 1);
            map.put("orderId", orderId);
            map.put("msg", "支付成功");
            return map;
        }
        try {
            // 非充值类型订单校验库存
            if (!welfareOrder.getOrderType().equals(WelfareOrderEnum.ORDER_TYPE_VIRTUAL_API_RECHARGE.getCode())) {
                searchValidLockAndQuantity(welfareOrder.getId());
            }
            // 校验卡余额
            searchValidSubCardRemain(welfareOrder.getId());
            map = weChatPay(welfareOrder, openId);
            return map;
        } catch (Exception e) {
            log.info("addPaymentExecute e: " + e.getMessage(), e);
            operationLogService.saveOrderReturnFail(orderId, e.toString());
            map.put("code", 1005);
            map.put("msg", e.getMessage());
            return map;
        }
    }

    /**
     * 扣减卡余额
     * @param orderId 订单ID
     * @return void
     * @author ChenLong
     * @date 2021-06-18 16:55:34
     **/
    private void updateSubCardRemain(Integer orderId) {
        // 扣减卡余额（从订单商品表获取已均摊的商品列表）
        List<WelfareOrderGoodsCardShareVo> orderGoodsCardShareList = mapper.getOrderGoodsCardShareListByOrderId(orderId);
        orderGoodsCardShareList.forEach(orderGoodsCardShare -> {
            if (EmptyUtils.isNotEmpty(orderGoodsCardShare.getCardSecretId())) {
                WelfareCardSecret welfareCardSecretRs = welfareCardSecretService.selectByPrimaryKey(orderGoodsCardShare.getCardSecretId());
                BigDecimal remainAmount = welfareCardSecretRs.getRemainAmount().subtract(orderGoodsCardShare.getTotalPaymentCredits());
                BigDecimal usedAmount = welfareCardSecretRs.getUsedAmount().add(orderGoodsCardShare.getTotalPaymentCredits());
                if (remainAmount.compareTo(BigDecimal.ZERO) < 0) {
                    throw new CommonException("积分扣减失败");
                }
                WelfareCardSecret welfareCardSecret = new WelfareCardSecret();
                welfareCardSecret.setId(orderGoodsCardShare.getCardSecretId());
                welfareCardSecret.setUsedAmount(usedAmount);
                welfareCardSecret.setRemainAmount(remainAmount);
                welfareCardSecret.setUpdateTime(new Date());
                welfareCardSecretService.updateByPrimaryKeySelective(welfareCardSecret);
            }
        });
    }

    /**
     * 扣减卡余额
     * @param orderId 订单ID
     * @return void
     * @author ChenLong
     * @date 2021-06-18 16:55:34
     **/
    private void searchValidSubCardRemain(Integer orderId) {
        // 扣减卡余额（从订单商品表获取已均摊的商品列表）
        List<WelfareOrderGoodsCardShareVo> orderGoodsCardShareList = mapper.getOrderGoodsCardShareListByOrderId(orderId);
        orderGoodsCardShareList.forEach(orderGoodsCardShare -> {
            if (EmptyUtils.isNotEmpty(orderGoodsCardShare.getCardSecretId())) {
                WelfareCardSecret welfareCardSecretRs = welfareCardSecretService.selectByPrimaryKey(orderGoodsCardShare.getCardSecretId());
                BigDecimal remainAmount = welfareCardSecretRs.getRemainAmount().subtract(orderGoodsCardShare.getTotalPaymentCredits());
                if (remainAmount.compareTo(BigDecimal.ZERO) < 0) {
                    throw new CommonException("卡余额不足");
                }
            }
        });
    }


    /**
     * 校验库存
     *
     * @param
     * @return void
     * @author ChenLong
     * @date 2021-07-13 12:29:23
     **/
    private void searchValidLockAndQuantity(Integer orderId) {
        // 扣减库存，释放预占
        List<WelfareOrderGoodsSkuVo> orderGoodsSkuList = mapper.getOrderGoodsSkuListByOrderId(orderId);
        orderGoodsSkuList.forEach(welfareOrderGoodsSkuVo -> {
            WelfareGoodsAttr welfareGoodsAttrRs = welfareGoodsAttrService.selectByPrimaryKey(welfareOrderGoodsSkuVo.getSkuId());
            WelfareGoodsAttr welfareGoodsAttr = new WelfareGoodsAttr();
            welfareGoodsAttr.setId(welfareOrderGoodsSkuVo.getSkuId());
            if (EmptyUtils.isNotEmpty(welfareGoodsAttrRs.getLockQuantity())) {
                Integer lastLockQuantity = welfareGoodsAttrRs.getLockQuantity() - welfareOrderGoodsSkuVo.getTotalGoodsQuantity();// 释放预占
                welfareGoodsAttr.setLockQuantity(lastLockQuantity);
            }
            Integer lastGoodsAttrQuantity = welfareGoodsAttrRs.getQuantity() - welfareOrderGoodsSkuVo.getTotalGoodsQuantity();// 扣减库存
            if (lastGoodsAttrQuantity < 0) {
                throw new CommonException("库存不足，请联系客服！");
            }
        });
    }

    /**
     * 释放预占和扣减库存
     *
     * @param
     * @return void
     * @author ChenLong
     * @date 2021-07-13 12:29:23
     **/
    private void updateReleaseLockAndSubQuantity(Integer orderId) {
        // 扣减库存，释放预占
        List<WelfareOrderGoodsSkuVo> orderGoodsSkuList = mapper.getOrderGoodsSkuListByOrderId(orderId);
        orderGoodsSkuList.forEach(welfareOrderGoodsSkuVo -> {
            WelfareGoodsAttr welfareGoodsAttrRs = welfareGoodsAttrService.selectByPrimaryKey(welfareOrderGoodsSkuVo.getSkuId());
            WelfareGoodsAttr welfareGoodsAttr = new WelfareGoodsAttr();
            welfareGoodsAttr.setId(welfareOrderGoodsSkuVo.getSkuId());
            if (EmptyUtils.isNotEmpty(welfareGoodsAttrRs.getLockQuantity())) {
                Integer lastLockQuantity = welfareGoodsAttrRs.getLockQuantity() - welfareOrderGoodsSkuVo.getTotalGoodsQuantity();// 释放预占
                welfareGoodsAttr.setLockQuantity(lastLockQuantity);
            }
            Integer lastGoodsAttrQuantity = welfareGoodsAttrRs.getQuantity() - welfareOrderGoodsSkuVo.getTotalGoodsQuantity();// 扣减库存
            if (lastGoodsAttrQuantity < 0) {
                throw new CommonException("库存不足，请联系客服！");
            }
            welfareGoodsAttr.setQuantity(lastGoodsAttrQuantity);
            welfareGoodsAttr.setUpdateTime(new Date());
            // 分布式Redis锁
            String key = RedisUtil.ORDER_RELEASE_LOCK_QUANTITY_PREFIX + welfareOrderGoodsSkuVo.getSkuId();
            RLock lock = RedisUtil.lock(key);
            try {
                if (lock.tryLock()) {
                    welfareGoodsAttrService.updateByPrimaryKeySelective(welfareGoodsAttr);

                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("updateReleaseLockAndSubQuantity e: " + e.getMessage(), e);
                throw new CommonException(e.getMessage());
            } finally {
                if (lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
            // 更新商品的兑换数量
            WelfareGoods welfareGoods = welfareGoodsService.selectByPrimaryKey(welfareGoodsAttrRs.getGoodsId());
            WelfareGoods welfareGoodsUpd = new WelfareGoods();
            welfareGoodsUpd.setId(welfareGoods.getId());
            welfareGoodsUpd.setGoodsConvertQuantity(welfareGoods.getGoodsConvertQuantity() + welfareOrderGoodsSkuVo.getTotalGoodsQuantity());
            welfareGoodsService.updateByPrimaryKeySelective(welfareGoodsUpd);
        });
    }

    /**
     * 订单拆单
     * @param welfareOrder 订单实体类
     * @return void
     * @author ChenLong
     * @date 2021-07-13 13:51:54
     **/
    @Master
    private void updateOrderSplitBySupplier(WelfareOrder welfareOrder, List<WelfareOrderGoods> welfareOrderGoodsListRes) {
        // 将订单下的商品以供应商id为key放入到map中
        Map<Integer, List<WelfareOrderGoods>> orderGoodsMap = new HashMap<>();
        if (EmptyUtils.isNotEmpty(welfareOrderGoodsListRes) && welfareOrderGoodsListRes.size() > 0) {
            for (WelfareOrderGoods welfareOrderGoods : welfareOrderGoodsListRes) {
                putOrderGoodsAddSupplier(orderGoodsMap, welfareOrderGoods.getSupplierId(), welfareOrderGoods);
            }
        }
        log.info("updateOrderAndSplitBySupplier welfareOrder: " + welfareOrder.toString());
        // 如果包含多个供应商信息，则需要拆单,如果只有一个供应商，则不拆单
        boolean isNeedSplitOrder = true;
        if (orderGoodsMap.size() < 2) {
            isNeedSplitOrder = false;
        }
        // 如果需要拆单
        if (isNeedSplitOrder) {
            // 将原来的订单头表数据软删除
            welfareOrder.setStatus(0);
            welfareOrder.setUpdateTime(new Date());
            mapper.updateByPrimaryKeySelective(welfareOrder);
            WelfareOrderGoods welfareOrderGoodsOld = new WelfareOrderGoods();
            welfareOrderGoodsOld.setOrderId(welfareOrder.getId());
            // 删除原订单下的订单商品记录
            welfareOrderGoodsService.delete(welfareOrderGoodsOld);
            // 拆单，重新分配商品ID，虚拟商品直接购买不存在拆单场景
            for (Map.Entry<Integer, List<WelfareOrderGoods>> entry : orderGoodsMap.entrySet()) {
                Integer supplierId = entry.getKey();
                WelfareOrder welfareOrderNew = new WelfareOrder();
                // 以供应商维度插入新的订单
                welfareOrderNew.setOrderNo(StringUtil.generateOrderNo());
                welfareOrderNew.setOldId(welfareOrder.getId());
                welfareOrderNew.setSupplierId(supplierId);
                welfareOrderNew.setUserId(welfareOrder.getUserId());
                if (welfareOrder.getEnterpriseId() != null) {
                    welfareOrderNew.setEnterpriseId(welfareOrder.getEnterpriseId());
                }
                //设置订单商品类型
                WelfareSupplier welfareSupplier = welfareSupplierService.selectByPrimaryKey(supplierId);
                if(welfareSupplier.getEnterpriseId().equals(CommonConstants.DEFAULT_PLATFORM_ENTERPRISE_ID)){
                    welfareOrder.setOrderGoodsType(CommonConstants.APP_GOODS_SOURCE.PLAFORM);
                }else{
                    welfareOrder.setOrderGoodsType(CommonConstants.APP_GOODS_SOURCE.SELF);
                }
                welfareOrderNew.setOrderType(welfareOrder.getOrderType());
                // 新订单地址设置，重新复制一份地址记录关联新拆的订单
                WelfareOrderAddress welfareOrderAddress = welfareOrderAddressService.selectByPrimaryKey(welfareOrder.getAddressId());
                welfareOrderAddress.setId(null);
                welfareOrderAddress.setCreateTime(new Date());
                welfareOrderAddressService.insertSelective(welfareOrderAddress);
                // 地址ID
                welfareOrderNew.setAddressId(welfareOrderAddress.getId());
                welfareOrderNew.setOutTradeNo(welfareOrder.getOutTradeNo());
                welfareOrderNew.setOtherTradeNo(welfareOrder.getOtherTradeNo());
                welfareOrderNew.setCreateTime(welfareOrder.getCreateTime());
                welfareOrderNew.setPayTime(new Date());
                welfareOrderNew.setUpdateTime(new Date());
                welfareOrderNew.setPaymentType(0);
                welfareOrderNew.setPaymentStatus(0);
                welfareOrderNew.setStatus(1);
                // 拆单的为实体订单，实体订单修改订单状态为待打款
                welfareOrderNew.setOrderStatus(WelfareOrderEnum.ORDER_STATUS_PRE_PAID.getCode());
                // 如果是兑换订单
                if (welfareOrder.getOrderType().equals(WelfareOrderEnum.ORDER_TYPE_EXCHANGE.getCode())) {
                    welfareOrderNew.setExchangeSecretId(welfareOrder.getExchangeSecretId());
                }
                Example example = new Example(WelfareOrderTempRemark.class);
                example.createCriteria().andEqualTo("orderId", welfareOrder.getId())
                        .andEqualTo("supplierId", supplierId);
                WelfareOrderTempRemark welfareOrderTempRemarkRes = welfareOrderTempRemarkService.selectOneByExample(example);
                if (EmptyUtils.isNotEmpty(welfareOrderTempRemarkRes) && EmptyUtils.isNotEmpty(welfareOrderTempRemarkRes.getRemark())) {
                    welfareOrderNew.setOrderRemark(welfareOrderTempRemarkRes.getRemark());
                }
                mapper.insert(welfareOrderNew);
                // 如果拆单了，插入订单商品信息；
                List<WelfareOrderGoods> welfareOrderGoodsList = entry.getValue();
                for (WelfareOrderGoods welfareOrderGoods : welfareOrderGoodsList) {
                    welfareOrderGoods.setOrderId(welfareOrderNew.getId());
                    welfareOrderGoods.setOrderIdOld(welfareOrder.getId());// 设置原订单id
                    welfareOrderGoods.setUpdateTime(new Date());
                }
                BigDecimal totalPaymentCredits = welfareOrderGoodsList.stream().filter(s -> s.getPaymentCredits() != null).map(WelfareOrderGoods::getPaymentCredits).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal totalPaymentAmount = welfareOrderGoodsList.stream().filter(s -> s.getPaymentAmount() != null).map(WelfareOrderGoods::getPaymentAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal totalAmount = totalPaymentCredits.add(totalPaymentAmount);
                welfareOrderGoodsService.insertList(welfareOrderGoodsList);
                // 更新订单支付信息
                WelfareOrder welfareOrderUpd = new WelfareOrder();
                welfareOrderUpd.setId(welfareOrderNew.getId());
                if (EmptyUtils.isNotEmpty(totalPaymentAmount)) {
                    welfareOrderUpd.setPaymentAmount(totalPaymentAmount);
                } else {
                    welfareOrderUpd.setPaymentAmount(BigDecimal.ZERO);
                }
                if (EmptyUtils.isNotEmpty(totalPaymentCredits)) {
                    welfareOrderUpd.setCreditsAmount(totalPaymentCredits);
                } else {
                    welfareOrderUpd.setCreditsAmount(BigDecimal.ZERO);
                }
                if (EmptyUtils.isNotEmpty(totalAmount)) {
                    welfareOrderUpd.setTotalAmount(totalAmount);
                } else {
                    welfareOrderUpd.setTotalAmount(BigDecimal.ZERO);
                }
                // 更新支付积分、支付金额
                mapper.updateByPrimaryKeySelective(welfareOrderUpd);
            }
        } else {
            // 如果不需要拆单，实体商品更新为待发货
            for (Map.Entry<Integer, List<WelfareOrderGoods>> entry : orderGoodsMap.entrySet()) {
                List<WelfareOrderGoods> welfareOrderGoodsList = entry.getValue();
                Integer supplierId = entry.getKey();
                for (WelfareOrderGoods welfareOrderGoods : welfareOrderGoodsList) {
                    welfareOrderGoods.setOrderIdOld(welfareOrder.getId());
                    welfareOrderGoodsService.updateByPrimaryKeySelective(welfareOrderGoods);
                }
                welfareOrder.setOrderStatus(WelfareOrderEnum.ORDER_STATUS_PRE_PAID.getCode());
                welfareOrder.setPayTime(new Date());
                welfareOrder.setOldId(welfareOrder.getId());
                welfareOrder.setUpdateTime(new Date());
                welfareOrder.setSupplierId(supplierId);
                // 设置订单备注
                Example example = new Example(WelfareOrderTempRemark.class);
                example.createCriteria().andEqualTo("orderId", welfareOrder.getId())
                        .andEqualTo("supplierId", supplierId);
                WelfareOrderTempRemark welfareOrderTempRemarkRes = welfareOrderTempRemarkService.selectOneByExample(example);
                if (EmptyUtils.isNotEmpty(welfareOrderTempRemarkRes) && EmptyUtils.isNotEmpty(welfareOrderTempRemarkRes.getRemark())) {
                    welfareOrder.setOrderRemark(welfareOrderTempRemarkRes.getRemark());
                }
                //设置订单商品类型
                WelfareSupplier welfareSupplier = welfareSupplierService.selectByPrimaryKey(supplierId);
                if(welfareSupplier.getEnterpriseId().equals(CommonConstants.DEFAULT_PLATFORM_ENTERPRISE_ID)){
                    welfareOrder.setOrderGoodsType(CommonConstants.APP_GOODS_SOURCE.PLAFORM);
                }else{
                    welfareOrder.setOrderGoodsType(CommonConstants.APP_GOODS_SOURCE.SELF);
                }
                mapper.updateByPrimaryKeySelective(welfareOrder);
            }
        }
    }

    /**
     * 更新虚拟订单信息，分配券密
     *
     * @param welfareOrderGoodsRes 订单商品
     * @param welfareOrder         订单实体
     * @return void
     * @author ChenLong
     * @date 2021-07-13 16:07:12
     **/
    private void updateVirtualOrderCompleted(WelfareOrderGoods welfareOrderGoodsRes, WelfareOrder welfareOrder) {
        // 虚拟商品不考虑拆单，虚拟商品只能购买一条（普通虚拟商品分配券密组）
        // 如果是虚拟订单，付款完以后更新为已完成
        welfareOrder.setOrderStatus(WelfareOrderEnum.ORDER_STATUS_COMPLETED.getCode());
        // 如果是普通虚拟订单，分配券密，并且更新订单商品表
        welfareOrderGoodsRes.setOrderIdOld(welfareOrder.getId());
        updateOrderAndVoucherSecretIds(welfareOrderGoodsRes, welfareOrder.getUserId());
        welfareOrderGoodsService.updateByPrimaryKeySelective(welfareOrderGoodsRes);
        welfareOrder.setPayTime(new Date());
        welfareOrder.setOldId(welfareOrder.getId());
        welfareOrder.setUpdateTime(new Date());
        welfareOrder.setSupplierId(welfareOrderGoodsRes.getSupplierId());
        // 设置订单备注
        Example example = new Example(WelfareOrderTempRemark.class);
        example.createCriteria().andEqualTo("orderId", welfareOrder.getId())
                .andEqualTo("supplierId", welfareOrderGoodsRes.getSupplierId());
        WelfareOrderTempRemark welfareOrderTempRemarkRes = welfareOrderTempRemarkService.selectOneByExample(example);
        if (EmptyUtils.isNotEmpty(welfareOrderTempRemarkRes) && EmptyUtils.isNotEmpty(welfareOrderTempRemarkRes.getRemark())) {
            welfareOrder.setOrderRemark(welfareOrderTempRemarkRes.getRemark());
        }
        mapper.updateByPrimaryKeySelective(welfareOrder);
    }

    @Override
    public void updateOrderAndSplitForPay(WelfareOrder welfareOrder) {
        // 兑换订单没有支付逻辑（拆单、核销、释放库存在提交完订单完就处理）
        log.info("updateOrderAndSplitForPay welfareOrder: " + welfareOrder.toString());
        // 扣减卡余额度
        updateSubCardRemain(welfareOrder.getId());
        if (welfareOrder.getOrderType().equals(WelfareOrderEnum.ORDER_TYPE_PHYSICAL.getCode())) {
            // 获取订单商品列表
            Example welfareOrderGoodsExample = new Example(WelfareOrderGoods.class);
            welfareOrderGoodsExample.createCriteria().andEqualTo("orderId", welfareOrder.getId());
            List<WelfareOrderGoods> welfareOrderGoodsListRes = welfareOrderGoodsService.selectByExample(welfareOrderGoodsExample);
            // 实体订单（普通实体订单、兑换订单）拆单、更新订单信息
            updateOrderSplitBySupplier(welfareOrder, welfareOrderGoodsListRes);
            // 释放预占和扣减库存、更新商品的兑换数量
            updateReleaseLockAndSubQuantity(welfareOrder.getId());
        } else if (welfareOrder.getOrderType().equals(WelfareOrderEnum.ORDER_TYPE_VIRTUAL.getCode())) {
            // 获取订单商品列表
            Example welfareOrderGoodsExample = new Example(WelfareOrderGoods.class);
            welfareOrderGoodsExample.createCriteria().andEqualTo("orderId", welfareOrder.getId());
            WelfareOrderGoods welfareOrderGoodsRes = welfareOrderGoodsService.selectOneByExample(welfareOrderGoodsExample);
            // 普通虚拟订单（分配券密、更新为完成）
            updateVirtualOrderCompleted(welfareOrderGoodsRes, welfareOrder);
            // 释放预占和扣减库存、更新商品的兑换数量
            updateReleaseLockAndSubQuantity(welfareOrder.getId());
            if (!welfareOrder.getEnterpriseId().equals(CommonConstants.DEFAULT_PLATFORM_ENTERPRISE_ID)) {
                // 扣减购买次数
                welfareUserPurchasesNumService.updateUserPurchasesNum(welfareOrder.getUserId(),welfareOrderGoodsRes.getGoodsId(),welfareOrderGoodsRes.getGoodsQuantity());
            }
        } else if (welfareOrder.getOrderType().equals(WelfareOrderEnum.ORDER_TYPE_VIRTUAL_API_RECHARGE.getCode())) {
            // 获取订单商品列表
            WelfareOrderGoodsProductVo welfareOrderGoodsProductRes = welfareOrderGoodsService.getOrderGoodsProductInfoByOrderId(welfareOrder.getId());
            Map<String, Object> resMap = new HashMap<>();
            // 如果是提卡接口则走提卡逻辑
            if (EmptyUtils.isNotEmpty(welfareOrder.getApiType()) && welfareOrder.getApiType().equals(WelfareOrderEnum.ORDER_API_TYPE_EXTRACT_CARD.getCode())){
            //if (EmptyUtils.isNotEmpty(welfareOrderGoodsProductRes) && welfareOrderGoodsProductRes.getMerchantId().equals(ApiExtractCardConstant.getMerchantId())){
                WelfareUserWx welfareUserWxRes = welfareUserWxService.selectByPrimaryKey(welfareOrder.getUserId());
                String phone = welfareUserWxRes.getPhone();
                extractCardService.extractCard(welfareOrderGoodsProductRes.getProductId(),welfareOrder.getId(),phone,welfareOrderGoodsProductRes.getGoodsQuantity());
            } else {
                // 充值类虚拟订单（调用充值）
                Order orderParams = new Order();
                orderParams.setOutTradeNo(welfareOrder.getOrderNo());
                orderParams.setOrderId(welfareOrder.getId());
                boolean ifTrue = validOrderGoodsProductAndBuildParams(resMap, welfareOrderGoodsProductRes, orderParams);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("map", resMap);
                jsonObject.put("orderParams", JsonUtils.objectToJson(orderParams));
                if (ifTrue) {
                    log.info("blueBrother recharge ing: " + jsonObject);
                    operationLogService.saveOrderReturnSuccess(welfareOrder.getId(), "blueBrother recharge ing: " + jsonObject);
                    String result = blueBrothersService.chargingForBlueBrotherOrFuLu(orderParams);
                    log.info("blueBrother recharge result: " + result);
                    operationLogService.saveOrderReturnSuccess(welfareOrder.getId(), "blueBrother recharge result: " + result);
                } else {
                    // 充值校验失败会记录日志
                    log.error("blueBrother recharge failed: " + jsonObject);
                    operationLogService.saveOrderReturnFail(welfareOrder.getId(), "blueBrother recharge failed: " + jsonObject);
                }
            }
            updateApiRechargeOrderCompleted(welfareOrderGoodsProductRes, welfareOrder);
            WelfareGoods welfareGoodsRes = welfareGoodsService.selectByPrimaryKey(welfareOrderGoodsProductRes.getGoodsId());
            // 更新商品的兑换数量
            WelfareGoods welfareGoodsUpd = new WelfareGoods();
            welfareGoodsUpd.setId(welfareOrderGoodsProductRes.getGoodsId());
            welfareGoodsUpd.setGoodsConvertQuantity(welfareGoodsRes.getGoodsConvertQuantity() + welfareOrderGoodsProductRes.getGoodsQuantity());
            welfareGoodsService.updateByPrimaryKeySelective(welfareGoodsUpd);
            if (!welfareOrder.getEnterpriseId().equals(CommonConstants.DEFAULT_PLATFORM_ENTERPRISE_ID)) {
                // 扣减购买次数
                welfareUserPurchasesNumService.updateUserPurchasesNum(welfareOrder.getUserId(),welfareOrderGoodsProductRes.getGoodsId(),welfareOrderGoodsProductRes.getGoodsQuantity());
            }
        }
    }

    /**
     * 校验订单商品及产品字段
     *
     * @param resMap                      返回Map
     * @param welfareOrderGoodsProductRes 订单商品对象
     * @param orderParams                 充值参数
     * @return boolean
     * @author ChenLong
     * @date 2021-07-14 15:04:50
     **/
    private boolean validOrderGoodsProductAndBuildParams(Map<String, Object> resMap, WelfareOrderGoodsProductVo welfareOrderGoodsProductRes, Order orderParams) {
        if (EmptyUtils.isEmpty(welfareOrderGoodsProductRes)) {
            resMap.put("msg", "无效的订单商品");
            return false;
        }
        if (EmptyUtils.isEmpty(welfareOrderGoodsProductRes.getProductId())) {
            resMap.put("msg", "无效的产品编码");
            return false;
        } else {
            orderParams.setProductId(Integer.parseInt(welfareOrderGoodsProductRes.getProductId()));
        }
        if (EmptyUtils.isEmpty(welfareOrderGoodsProductRes.getAccount())) {
            resMap.put("msg", "无效的充值帐号");
            return false;
        } else {
            orderParams.setRechargeAccount(welfareOrderGoodsProductRes.getAccount());
        }
        if (EmptyUtils.isEmpty(welfareOrderGoodsProductRes.getMerchantId())) {
            resMap.put("msg", "无效的商户Id");
            return false;
        } else {
            orderParams.setMerchantId(welfareOrderGoodsProductRes.getMerchantId());
        }
        if (EmptyUtils.isEmpty(welfareOrderGoodsProductRes.getGoodsQuantity())) {
            resMap.put("msg", "无效的商品数量");
            return false;
        } else {
            orderParams.setNumber(welfareOrderGoodsProductRes.getGoodsQuantity());
        }
        resMap.put("data", welfareOrderGoodsProductRes.toString());
        resMap.put("params", orderParams.toString());
        return true;
    }

    /**
     * 更新虚拟订单信息，分配券密
     * @param welfareOrderGoodsRes 订单商品
     * @param welfareOrder         订单实体
     * @return void
     * @author ChenLong
     * @date 2021-07-13 16:07:12
     **/
    private void updateApiRechargeOrderCompleted(WelfareOrderGoodsProductVo welfareOrderGoodsRes, WelfareOrder welfareOrder) {
        // 虚拟商品不考虑拆单，虚拟商品只能购买一条（普通虚拟商品分配券密组）
        // 如果是虚拟订单，付款完以后更新为已完成
        welfareOrder.setOrderStatus(WelfareOrderEnum.ORDER_STATUS_COMPLETED.getCode());
        welfareOrderGoodsRes.setOrderIdOld(welfareOrder.getId());
        if (EmptyUtils.isNotEmpty(welfareOrder.getApiType()) && welfareOrder.getApiType().equals(WelfareOrderEnum.ORDER_API_TYPE_EXTRACT_CARD.getCode())){
            welfareOrder.setApiStatus(1);
        }
        welfareOrderGoodsService.updateByPrimaryKeySelective(welfareOrderGoodsRes);
        welfareOrder.setPayTime(new Date());
        welfareOrder.setOldId(welfareOrder.getId());
        welfareOrder.setUpdateTime(new Date());
        welfareOrder.setSupplierId(welfareOrderGoodsRes.getSupplierId());
        // 设置订单备注
        Example example = new Example(WelfareOrderTempRemark.class);
        example.createCriteria().andEqualTo("orderId", welfareOrder.getId())
                .andEqualTo("supplierId", welfareOrderGoodsRes.getSupplierId());
        WelfareOrderTempRemark welfareOrderTempRemarkRes = welfareOrderTempRemarkService.selectOneByExample(example);
        if (EmptyUtils.isNotEmpty(welfareOrderTempRemarkRes) && EmptyUtils.isNotEmpty(welfareOrderTempRemarkRes.getRemark())) {
            welfareOrder.setOrderRemark(welfareOrderTempRemarkRes.getRemark());
        }
        mapper.updateByPrimaryKeySelective(welfareOrder);
    }

    /**
     * 分配券密组
     *
     * @param welfareOrderGoods 订单商品实体类
     * @return void
     * @author ChenLong
     * @date 2021-06-15 22:10:15
     **/
    private void updateOrderAndVoucherSecretIds(WelfareOrderGoods welfareOrderGoods, Integer userId) {
        // 去指定的券密组里面取指定个券密
        List<WelfareVoucherSecret> voucherSecretList = welfareVoucherSecretService.getVoucherSecretListLimitByQuantity(welfareOrderGoods.getGoodsQuantity(), welfareOrderGoods.getSkuId());
        List<Integer> idList = new ArrayList<>();
        StringBuilder idListSb = new StringBuilder();
        if (EmptyUtils.isNotEmpty(voucherSecretList) && voucherSecretList.size() > 0) {
            for (WelfareVoucherSecret welfareVoucherSecret : voucherSecretList) {
                idList.add(welfareVoucherSecret.getId());
                idListSb.append(welfareVoucherSecret.getId()).append(",");
            }
            // 更新券密兑换人、状态为已兑换
            Example welfareVoucherSecretExample = new Example(WelfareVoucherSecret.class);
            welfareVoucherSecretExample.createCriteria().andIn("id", idList);
            WelfareVoucherSecret welfareVoucherSecretUpd = new WelfareVoucherSecret();
            welfareVoucherSecretUpd.setIsSell(0);
            welfareVoucherSecretUpd.setSellTime(new Date());
            welfareVoucherSecretUpd.setSellUserId(userId);
            welfareVoucherSecretUpd.setUpdateTime(new Date());
            welfareVoucherSecretService.updateByExampleSelective(welfareVoucherSecretUpd, welfareVoucherSecretExample);
            String idListStr = idListSb.substring(0, idListSb.length() - 1);
            welfareOrderGoods.setSecretIds(idListStr);
        }
    }

    /**
     * 微信支付
     * @param welfareOrder 订单实体类
     * @param openId       微信openId
     * @return java.util.Map
     * @author ChenLong
     * @date 2021-06-06 12:42:04
     **/
    private Map weChatPay(WelfareOrder welfareOrder, String openId) throws Exception {
        log.info("weChatPay in: " + welfareOrder.toString());
        Map<String, Object> map = new HashMap<>();
        // 微信支付
        if (EmptyUtils.isEmpty(welfareOrder.getPaymentAmount())) {
            throw new CommonException("现金支付异常");
        }
        // 微信支付日志JSONObject
        JSONObject logJsonObj = new JSONObject();
        BigDecimal totalFee = WXPayUtil.calcWxPayPrice(welfareOrder.getPaymentAmount());
        log.info("weChatPay totalFee: " + totalFee);
        String body = "企福产品购买";
        WelfareEnterprise welfareEnterprise = welfareEnterpriseService.selectByPrimaryKey(welfareOrder.getEnterpriseId());
        if(EmptyUtils.isEmpty(welfareEnterprise) || EmptyUtils.isEmpty(welfareEnterprise.getAppid()) || EmptyUtils.isEmpty(welfareEnterprise.getAppsecret())
                || EmptyUtils.isEmpty(welfareEnterprise.getMchId()) || EmptyUtils.isEmpty(welfareEnterprise.getMchKey())){
            throw new CommonException("现金支付异常:缺少小程序独立部署配置参数");
        }
        String xml = WXPayUtil.generateSignature(welfareEnterprise.getAppid(), welfareEnterprise.getMchId(), welfareEnterprise.getMchKey(), WxConfig.PAY_NOTIFY_SETTLEMENT_URL, totalFee, welfareOrder.getOutTradeNo(), openId, body);
        log.info("weChatPay param: getEnterpriseId:" + welfareOrder.getEnterpriseId()+",appid:"+welfareEnterprise.getAppid()+",appsecret:"+welfareEnterprise.getAppsecret()
                +",mchid:"+welfareEnterprise.getMchId()+",mchkey:"+welfareEnterprise.getMchKey()+",xml is "+xml);
        /*String xml = WXPayUtil.generateSignature(WxConfig.WX_XCX_APPID, WxConfig.WX_PARTNER, WxConfig.WX_P
        ARTNER_KEY,
                WxConfig.PAY_NOTIFY_SETTLEMENT_URL, totalFee, welfareOrder.getOutTradeNo(), openId, body);*/
        Object result = HttpRequest.post(WxConfig.PAY_UNIFIEDORDER_URL, xml, 0);
        log.info("weChatPay result: " + result);
        if (EmptyUtils.isEmpty(result)) {
            logJsonObj.put("code", 1003);
            logJsonObj.put("params", xml);
            logJsonObj.put("outTradeNo", welfareOrder.getOutTradeNo());
            operationLogService.saveOrderReturnFail(welfareOrder.getId(), "WeChat pay failed: " + logJsonObj.toString());
            map.put("code", 1003);
            map.put("msg", "微信支付失败");
            return map;
        }
        Map<String, String> resultMap = WXPayUtil.readStringXmlOut(result.toString());
        if ((WXPayConstants.SUCCESS).equals(MapUtils.getString(resultMap, "result_code"))) {
            String prepayId = resultMap.get("prepay_id");
            Map mapRes = WXPayUtil.signMapById(welfareEnterprise.getAppid(), prepayId, welfareEnterprise.getMchKey());
            // 微信支付日志JSONObject
            logJsonObj.put("code", 1);
            logJsonObj.put("params", xml);
            logJsonObj.put("result", result);
            logJsonObj.put("outTradeNo", welfareOrder.getOutTradeNo());
            operationLogService.saveOrderReturnSuccess(welfareOrder.getId(), "WeChat pay success: " + logJsonObj.toString());
            mapRes.put("orderId", welfareOrder.getId());
            mapRes.put("code", 1);
            mapRes.put("msg", "success");
            return mapRes;
        } else {
            // 微信支付日志JSONObject
            logJsonObj.put("code", 1004);
            logJsonObj.put("params", xml);
            logJsonObj.put("result", result);
            logJsonObj.put("outTradeNo", welfareOrder.getOutTradeNo());
            operationLogService.saveOrderReturnFail(welfareOrder.getId(), "WeChat pay failed: " + logJsonObj.toString());
            map.put("code", 1004);
            map.put("msg", "微信支付失败");
            return map;
        }
    }

    /**
     * 以供应商为纬度拆单
     * @param map               以供应商id为key，订单商品列表为value的map
     * @param supplierId        供应商id
     * @param welfareOrderGoods 订单商品列表
     * @return void
     * @author ChenLong
     * @date 2021-06-06 12:36:17
     **/
    private void putOrderGoodsAddSupplier(Map<Integer, List<WelfareOrderGoods>> map, Integer supplierId, WelfareOrderGoods welfareOrderGoods) {
        List<WelfareOrderGoods> welfareOrderGoodsDtoList;
        if (map.containsKey(supplierId)) {
            welfareOrderGoodsDtoList = map.get(supplierId);
            welfareOrderGoodsDtoList.add(welfareOrderGoods);
        } else {
            welfareOrderGoodsDtoList = new ArrayList<>();
            welfareOrderGoodsDtoList.add(welfareOrderGoods);
        }
        map.put(supplierId, welfareOrderGoodsDtoList);
    }

    @Override
    public Integer cancelOrderByOrderId(WelfareOrderCancelDto welfareOrderCancelDto) {
        WelfareOrder welfareOrderUpd = new WelfareOrder();
        welfareOrderUpd.setId(welfareOrderCancelDto.getId());
        if (EmptyUtils.isNotEmpty(welfareOrderCancelDto.getUserId())) {
            welfareOrderUpd.setUserId(welfareOrderCancelDto.getUserId());
        }
        welfareOrderUpd.setOrderStatus(WelfareOrderEnum.ORDER_STATUS_CANCEL.getCode());
        if (EmptyUtils.isNotEmpty(welfareOrderCancelDto.getRemark())) {
            welfareOrderUpd.setRemark(welfareOrderCancelDto.getRemark());
        }
        welfareOrderUpd.setUpdateTime(new Date());
        WelfareUserWx welfareUserWxRes = welfareUserWxService.selectByPrimaryKey(welfareOrderCancelDto.getUserId());
        if (EmptyUtils.isNotEmpty(welfareUserWxRes) && EmptyUtils.isNotEmpty(welfareUserWxRes.getPhone())) {
            welfareOrderUpd.setUpdaterName(welfareUserWxRes.getPhone());
        }
        mapper.updateByPrimaryKeySelective(welfareOrderUpd);
        // 充值类订单没有库存和预占
        if (!welfareOrderCancelDto.getOrderType().equals(WelfareOrderEnum.ORDER_TYPE_VIRTUAL_API_RECHARGE.getCode())) {
            releaseGoodsLockByOrderId(welfareOrderCancelDto.getId());
        }
        return 1;
    }

    @Override
    public Integer updateOrderRemark(WelfareOrderSignUpdDro welfareOrderSignUpdDro) {
        WelfareOrder welfareOrderUpd = new WelfareOrder();
        welfareOrderUpd.setId(welfareOrderSignUpdDro.getOrderId());
        welfareOrderUpd.setSignDes(welfareOrderSignUpdDro.getSignDes());
        return mapper.updateByPrimaryKeySelective(welfareOrderUpd);
    }

    /**
     * 释放预占
     * @param orderId 订单id
     * @return void
     * @author ChenLong
     * @date 2021-06-22 20:11:32
     **/
    private void releaseGoodsLockByOrderId(Integer orderId) {
        WelfareOrderGoods welfareOrderGoodsSelect = new WelfareOrderGoods();
        welfareOrderGoodsSelect.setOrderId(orderId);
        List<WelfareOrderGoods> welfareOrderGoodsList = welfareOrderGoodsService.select(welfareOrderGoodsSelect);
        List<Integer> skuIdList = welfareOrderGoodsList.stream().map(WelfareOrderGoods::getSkuId).collect(Collectors.toList());
        Map<Integer, Integer> skuLockMap = new HashMap<>();
        for (WelfareOrderGoods welfareOrderGoods : welfareOrderGoodsList) {
            Integer skuId = welfareOrderGoods.getSkuId();
            Integer goodsQuantity = welfareOrderGoods.getGoodsQuantity();
            if (skuLockMap.containsKey(skuId) && EmptyUtils.isNotEmpty(skuLockMap.get(skuId))) {
                skuLockMap.put(skuId, skuLockMap.get(skuId) + goodsQuantity);
            } else {
                skuLockMap.put(skuId, goodsQuantity);
            }
        }
        Example welfareOrderGoodsAttrExample = new Example(WelfareGoodsAttr.class);
        welfareOrderGoodsAttrExample.createCriteria().andIn("id", skuIdList);
        List<WelfareGoodsAttr> welfareGoodsAttrList = welfareGoodsAttrService.selectByExample(welfareOrderGoodsAttrExample);
        for (WelfareGoodsAttr welfareGoodsAttr : welfareGoodsAttrList) {
            WelfareGoodsAttr welfareGoodsAttrUpd = new WelfareGoodsAttr();
            welfareGoodsAttrUpd.setId(welfareGoodsAttr.getId());
            Integer afterLockQuantity = welfareGoodsAttr.getLockQuantity() - skuLockMap.get(welfareGoodsAttr.getId());// 释放预占
            if (afterLockQuantity > 0) {
                welfareGoodsAttrUpd.setLockQuantity(afterLockQuantity);
            } else {
                welfareGoodsAttrUpd.setLockQuantity(0);
            }
            welfareGoodsAttrService.updateByPrimaryKeySelective(welfareGoodsAttrUpd);
        }
    }

    @Override
    public Integer updateOrderCancelExpiredTime() {
        Integer resCode = 0;
        // 分布式Redis锁
        String key = RedisUtil.ORDER_CANCEL_LOCK_PREFIX;
        RLock lock = RedisUtil.lock(key);
        try {
            if (lock.tryLock(2, TimeUnit.SECONDS)) {
                List<WelfareOrder> welfareOrderList = mapper.getOrderCancelExpiredTime();
                List<Integer> orderIdList = new ArrayList<>();
                for (WelfareOrder welfareOrder : welfareOrderList) {
                    // 充值类订单没有库存和预占
                    if (!welfareOrder.getOrderType().equals(WelfareOrderEnum.ORDER_TYPE_VIRTUAL_API_RECHARGE.getCode())) {
                        releaseGoodsLockByOrderId(welfareOrder.getId());
                    }
                    orderIdList.add(welfareOrder.getId());
                }
                if (EmptyUtils.isNotEmpty(orderIdList)) {
                    WelfareOrder welfareOrderUpd = new WelfareOrder();
                    welfareOrderUpd.setOrderStatus(WelfareOrderEnum.ORDER_STATUS_CANCEL.getCode());
                    welfareOrderUpd.setRemark("超时未支付");
                    welfareOrderUpd.setUpdateTime(new Date());
                    Example welfareOrderExample = new Example(WelfareOrder.class);
                    welfareOrderExample.createCriteria().andIn("id", orderIdList);
                    resCode = mapper.updateByExampleSelective(welfareOrderUpd, welfareOrderExample);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("updateOrderCancelExpiredTime e: " + e.getMessage(), e);
            throw new CommonException(e.getMessage());
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
        return resCode;
    }

    @Override
    public PageInfo<WelfareSupplier> getOrderSupplierListPage(WelfareOrderQuery query) {
        PageHelper.startPage(query);
        List<WelfareSupplier> list = mapper.getOrderSupplierList(query);
        PageInfo<WelfareSupplier> page = new PageInfo<WelfareSupplier>(list);
        return page;
    }

    @Master
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer batchDelivery(List<OrderBatchDeliveryDto> dtoList, LoginSysAdminVo admin) {
        //先查询这些订单中是否有不是待发货的
        List<String> orderNos = dtoList.stream().map(OrderBatchDeliveryDto::getOrderNo).collect(Collectors.toList());
        Integer deliveryOrderStatus = WelfareOrderEnum.ORDER_STATUS_PAID.getCode();
        int countDelivery = mapper.selectCountByOrderIds(orderNos, deliveryOrderStatus);
        if (countDelivery < dtoList.size()) {
            throw new CommonException("有订单不是待发货状态，无法发货！");
        }
        //通过订单编号查询订单
        Integer countByOrderNos = mapper.selectCountByOrderNos(orderNos);
        if (countByOrderNos < orderNos.size()) {
            throw new CommonException("有订单编号被改动！");
        }
        Date updateTime = new Date();
        for (OrderBatchDeliveryDto dto : dtoList) {
            //通过订单编号查询订单
            WelfareOrder welfareOrderQuery = new WelfareOrder();
            welfareOrderQuery.setOrderNo(dto.getOrderNo());
            WelfareOrder welfareOrder = mapper.selectOne(welfareOrderQuery);
            //通过物流公司名称查询code
            //首先如果此行的快递公司名称填了
            if (EmptyUtils.isNotEmpty(dto.getExpressName().trim())) {
                WelfareExpress welfareExpress = new WelfareExpress();
                welfareExpress.setName(dto.getExpressName().trim());
                welfareExpress.setState(1);
                //查询匹配的code
                List<WelfareExpress> welfareExpressList = welfareExpressService.select(welfareExpress);
                //如果可以匹配上
                if (!CollectionUtils.isEmpty(welfareExpressList)) {
                    //更改发货状态
                    WelfareOrderExpress welfareOrderExpress = new WelfareOrderExpress();
                    welfareOrderExpress.setOrderId(welfareOrder.getId());
                    welfareOrderExpress.setCreateTime(new Date());
                    welfareOrderExpress.setExpressCode(welfareExpressList.get(0).getCode().replace(" ", ""));
                    welfareOrderExpress.setExpressName(welfareExpressList.get(0).getName().replace(" ", ""));
                    if (EmptyUtils.isNotEmpty(dto.getExpressNo().replace(" ", ""))) {
                        welfareOrderExpress.setExpressNo(dto.getExpressNo().replace(" ", ""));
                    }
                    welfareOrderExpressService.insertSelective(welfareOrderExpress);
                } else {
                    throw new CommonException("导入表格有快递公司填写有误！");
                }
            } else {
                throw new CommonException("导入表格有快递公司未填写！");
            }
            //更改订单表数据
            welfareOrder.setOrderStatus(WelfareOrderEnum.ORDER_STATUS_SHIPED.getCode());
            welfareOrder.setUpdater(admin.getId());
            welfareOrder.setUpdaterName(admin.getUserName());
            welfareOrder.setUpdateTime(updateTime);
            welfareOrder.setDeliveryTime(updateTime);
            welfareOrder.setDeliveryUserId(admin.getId());
            welfareOrder.setDeliveryUserName(admin.getUserName());
            mapper.updateByPrimaryKeySelective(welfareOrder);
        }
        return dtoList.size();
    }

    @Master
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer orderDelivery(List<OrderBatchDeliveryDto> dtoList, LoginSysAdminVo adminVo) {
        Date updateTime = new Date();
        int count = 0;
        int orderIdOut = 0;
        for (OrderBatchDeliveryDto dto : dtoList) {
            //通过订单ID查询订单
            WelfareOrder welfareOrder = mapper.selectByPrimaryKey(dto.getOrderId());
            //如果是该比订单第一次进for循环，for循环外orderId赋值为当前订单id
            Integer orderStatus = welfareOrder.getOrderStatus();
            if (count == 0) {
                //进行各种判断
                if (orderStatus.equals(WelfareOrderEnum.ORDER_STATUS_UNPAY.getCode())) {
                    throw new CommonException("订单处于待支付状态，无法发货！");
                }
                if (orderStatus.equals(WelfareOrderEnum.ORDER_STATUS_COMPLETED.getCode())) {
                    //throw new CommonException("订单处于已完成状态，无法发货！");
                    //已完成订单只更改发货信息
                }
                if (orderStatus.equals(WelfareOrderEnum.ORDER_STATUS_CANCEL.getCode())) {
                    throw new CommonException("订单处于已取消状态，无法发货！");
                }
                if (orderStatus.equals(WelfareOrderEnum.ORDER_STATUS_NO_DELIVERY_REFUND.getCode())
                        || orderStatus.equals(WelfareOrderEnum.ORDER_STATUS_DELIVERY_REFUND.getCode())) {
                    throw new CommonException("订单处于已退款状态，无法发货！");
                }
                orderIdOut = welfareOrder.getId();
                //可能是更改订单发货信息
                //先根据orderId删除订单物流表的数据
                welfareOrderExpressService.deleteByOrderId(dto.getOrderId());
            }
            //如果当前订单id等于外部订单id
            if (welfareOrder.getId().equals(orderIdOut)) {
                count += 1;
            } else {
                //否则，则说明是下一笔订单的第一个物流，count重置为0
                count = 0;
            }
            //count为0，才判断该订单是否是代发货状态，如果不是0，则说明已经是该订单的第二个物流，不判断订单是否待发货
            if (count == 0 && !welfareOrder.getOrderStatus().equals(WelfareOrderEnum.ORDER_STATUS_PAID.getCode())) {
                throw new CommonException("订单不是待发货，无法发货！");
            }
            if (!welfareOrder.getId().equals(dto.getOrderId())) {
                throw new CommonException("订单编号与订单ID对应不上，无法发货！");
            }
            //通过物流公司名称查询code
            WelfareExpress welfareExpress = new WelfareExpress();
            welfareExpress.setCode(dto.getExpressCode());
            welfareExpress.setState(1);
            //查询匹配的code
            List<WelfareExpress> welfareExpressList = welfareExpressService.select(welfareExpress);
            //更改发货状态
            WelfareOrderExpress welfareOrderExpress = new WelfareOrderExpress();
            welfareOrderExpress.setOrderId(welfareOrder.getId());
            welfareOrderExpress.setCreateTime(new Date());
            welfareOrderExpress.setExpressCode(welfareExpressList.get(0).getCode().replace(" ", ""));
            welfareOrderExpress.setExpressName(welfareExpressList.get(0).getName().replace(" ", ""));
            if (EmptyUtils.isNotEmpty(dto.getExpressNo().replace(" ", ""))) {
                welfareOrderExpress.setExpressNo(dto.getExpressNo().replace(" ", ""));
            }
            welfareOrderExpressService.insertSelective(welfareOrderExpress);
            //更改订单表数据
            //未完成的订单更改物流信息时才更改发货状态，已完成订单更改发货信息不需要更改订单状态
            if (!orderStatus.equals(WelfareOrderEnum.ORDER_STATUS_COMPLETED.getCode())) {
                welfareOrder.setOrderStatus(WelfareOrderEnum.ORDER_STATUS_SHIPED.getCode());
            }
            welfareOrder.setUpdater(adminVo.getId());
            welfareOrder.setUpdaterName(adminVo.getUserName());
            welfareOrder.setUpdateTime(updateTime);
            welfareOrder.setDeliveryTime(updateTime);
            welfareOrder.setDeliveryUserId(adminVo.getId());
            welfareOrder.setDeliveryUserName(adminVo.getUserName());
            mapper.updateByPrimaryKeySelective(welfareOrder);
            count += 1;
        }
        return count;
    }

    @Override
    public Integer cancelOrder(WelfareOrder welfareOrder) {
        WelfareOrder welfareOrder2 = mapper.selectByPrimaryKey(welfareOrder.getId());
        Integer orderStatus = welfareOrder2.getOrderStatus();
        if (welfareOrder.getRemark().equals("超时未支付") && orderStatus.equals(WelfareOrderEnum.ORDER_STATUS_CANCEL.getCode())) {
            return 0;
        } else {
            if (!orderStatus.equals(WelfareOrderEnum.ORDER_STATUS_UNPAY.getCode())) {
                throw new CommonException("订单不是待付款状态，无法取消！");
            }
            if (welfareOrder2.getStatus().equals(0)) {
                throw new CommonException("该订单已被拆单，无法取消！");
            }
            //释放预占
            releaseGoodsLockByOrderId(welfareOrder.getId());
            //更新订单表
            WelfareOrder welfareOrder1 = new WelfareOrder();
            welfareOrder1.setId(welfareOrder.getId());
            welfareOrder1.setUpdateTime(new Date());
            welfareOrder1.setUpdater(welfareOrder.getUpdater());
            welfareOrder1.setUpdaterName(welfareOrder.getUpdaterName());
            welfareOrder1.setRemark(welfareOrder.getRemark());
            welfareOrder1.setOrderStatus(WelfareOrderEnum.ORDER_STATUS_CANCEL.getCode());
            return mapper.updateByPrimaryKeySelective(welfareOrder1);
        }
    }

    @Master
    @Override
    public Integer updateRefundOrder(WelfareOrder welfareOrder) {
        String refundNo = String.valueOf(System.currentTimeMillis());
        Integer orderId = welfareOrder.getId();
        //是否发送退款短信短信 0不发，1发
        int isSendMsg;
        //锁住
        String key = RedisUtil.ORDER_REFUND_LOCK_PREFIX + orderId;
        RLock rLock = RedisUtil.lock(key);
        try {
            if (rLock.tryLock(15, TimeUnit.SECONDS)) {
                //查询当前订单
                WelfareOrder welfareOrder2 = mapper.selectByPrimaryKey(orderId);
                Integer orderStatus = welfareOrder2.getOrderStatus();
                if (orderStatus.equals(WelfareOrderEnum.ORDER_STATUS_UNPAY.getCode())) {
                    throw new CommonException("订单待付款，无法退款！");
                }
                if (orderStatus.equals(WelfareOrderEnum.ORDER_STATUS_CANCEL.getCode())) {
                    throw new CommonException("订单已取消，无法退款！");
                }
                if (orderStatus.equals(WelfareOrderEnum.ORDER_STATUS_NO_DELIVERY_REFUND.getCode())
                        || orderStatus.equals(WelfareOrderEnum.ORDER_STATUS_DELIVERY_REFUND.getCode())) {
                    throw new CommonException("订单已退款，无法退款！");
                }
                // 微信收取的总金额，拆单后需要查询原订单金额
                //查询订单旧订单
                WelfareOrder oldOrder = mapper.selectByPrimaryKey(welfareOrder2.getOldId());
                //退款金额
                BigDecimal refundAmount = welfareOrder2.getPaymentAmount();
                //退款积分
                BigDecimal refundPoints = welfareOrder2.getCreditsAmount();
                if (welfareOrder2.getEnterpriseId().equals(0)) {
                    isSendMsg = 1; //发送退款短信
                    //为0 福利兔 兔福宝 是卡支付
                    //查询订单各卡支付信息
                    List<OrderPayCardVo> orderPayCardVoList = welfareOrderGoodsService.selectOrderPayCarVo(orderId);
                    orderPayCardVoList.forEach(orderPayCardVo -> {
                        Integer cardSecretId = orderPayCardVo.getCardSecretId();
                        BigDecimal cardPayAmount = orderPayCardVo.getCardPayAmount();
                        //如果有卡密id就说明这笔订单有卡参与支付
                        if (EmptyUtils.isNotEmpty(cardSecretId)) {
                            //通过卡密id找到这张卡
                            WelfareCardSecret welfareCardSecret = welfareCardSecretService.selectByPrimaryKey(cardSecretId);
                            if (EmptyUtils.isEmpty(welfareCardSecret)) {
                                throw new CommonException("该卡数据已丢失！");
                            }
                            BigDecimal totalAmount = welfareCardSecret.getTotalAmount();
                            BigDecimal usedAmount = welfareCardSecret.getUsedAmount();
                            BigDecimal remainAmount = welfareCardSecret.getRemainAmount();
                            BigDecimal putInAmount = welfareCardSecret.getPutInAmount();
                            BigDecimal putOutAmount = welfareCardSecret.getPutOutAmount();
                            usedAmount = usedAmount.subtract(cardPayAmount);
                            remainAmount = remainAmount.add(cardPayAmount);
                            if ((usedAmount.add(remainAmount).subtract(putInAmount).add(putOutAmount)).compareTo(totalAmount) != 0) {
                              //  throw new CommonException("退款后积分总额对不上，无法进行退款！");
                            }
                            if (usedAmount.compareTo(BigDecimal.ZERO) < 0) {
                               // throw new CommonException("退款后已用积分变为负数，测试脏数据有误，无法退款！");
                            }
                            welfareCardSecret.setUpdater(welfareOrder.getUpdater());
                            welfareCardSecret.setUpdateTime(new Date());
                            welfareCardSecret.setUsedAmount(usedAmount);
                            welfareCardSecret.setRemainAmount(remainAmount);
                            welfareCardSecretService.updateByPrimaryKeySelective(welfareCardSecret);
                        }
                    });
                } else {
                    isSendMsg = 0; //不发退款短信
                    //否则是积分支付
                    WelfareUserWx welfareUserWx = welfareUserWxService.selectByPrimaryKey(oldOrder.getUserId());
                    WelfareUserWx newUserWx = new WelfareUserWx();
                    newUserWx.setId(welfareUserWx.getId());
                    newUserWx.setBalanceIntegral(welfareUserWx.getBalanceIntegral().add(welfareOrder2.getCreditsAmount())); //退积分余额
                    newUserWx.setConsumeIntegral(welfareUserWx.getConsumeIntegral().subtract(welfareOrder2.getCreditsAmount())); //扣已使用积分
                    if ((newUserWx.getBalanceIntegral().add(newUserWx.getConsumeIntegral()).add(welfareUserWx.getExpiredIntegral())).compareTo(welfareUserWx.getTotalIntegral()) != 0) {
                        //退款后 积分余额+已用积分不等于总积分
                        throw new CommonException("退款后积分总额对不上，无法进行退款！");
                    }
                    welfareUserWxService.updateByPrimaryKeySelective(newUserWx);
                    //给用户退积分也要写入积分详情表
                    WelfareIntegralGrantDetail integralGrantDetail = new WelfareIntegralGrantDetail();
                    integralGrantDetail.setType(4);
                    integralGrantDetail.setCreateTime(new Date());
                    integralGrantDetail.setUserId(welfareUserWx.getId());
                    integralGrantDetail.setGrantIntegral(welfareOrder2.getCreditsAmount());
                    welfareIntegralGrantDetailService.insertSelective(integralGrantDetail);
                }
                //退款人民币
                try {
                    // 微信退还订单金额
                    //微信订单总金额，即旧订单支付现金金额
                    BigDecimal totalPrice = WXPayUtil.calcWxPayPrice(oldOrder.getPaymentAmount());
                    //退款金额
                    BigDecimal returnPrice = WXPayUtil.calcWxPayPrice(welfareOrder2.getPaymentAmount());
                    if (returnPrice.compareTo(BigDecimal.ZERO) > 0) {
                        if (totalPrice.compareTo(returnPrice) < 0) {
                            String errLog = "微信退款失败, 退款金额不能大于实际支付金额, 请检查订单是否为测试订单";
                            log.error(errLog);
                            operationLogService.saveOrderReturnFail(orderId, errLog);
                            throw new CommonException("微信退款失败, 退款金额不能大于实际支付金额, 请检查订单是否为测试订单");
                        } else {
                            log.info("======================updateRefundOrder orderId is "+welfareOrder2.getId()+", enterpriseId is "+welfareOrder2.getEnterpriseId());
                            WelfareEnterprise welfareEnterprise = welfareEnterpriseService.selectByPrimaryKey(welfareOrder2.getEnterpriseId());
                            if(EmptyUtils.isEmpty(welfareEnterprise) || EmptyUtils.isEmpty(welfareEnterprise.getAppid()) || EmptyUtils.isEmpty(welfareEnterprise.getAppsecret())
                                    || EmptyUtils.isEmpty(welfareEnterprise.getMchId()) || EmptyUtils.isEmpty(welfareEnterprise.getMchKey())){
                                throw new CommonException("微信退款失败:缺少小程序独立部署配置参数");
                            }
                            String xml = WXPayUtil.generateRefundSignature(welfareEnterprise.getAppid(), welfareEnterprise.getMchId(), welfareEnterprise.getMchKey(), totalPrice, returnPrice, welfareOrder2.getOutTradeNo(), refundNo);
                            String wxResponse = HttpRequest.doCertificatePost(welfareEnterprise.getMchId(), WxConfig.REFUND_URL, xml, WxConfig.getXcxCertPath());
                            /*String xml = WXPayUtil.generateRefundSignature(WxConfig.WX_XCX_APPID, WxConfig.WX_PARTNER, WxConfig.WX_PARTNER_KEY, totalPrice, returnPrice, welfareOrder2.getOutTradeNo(), refundNo);
                            String wxResponse = HttpRequest.doCertificatePost(WxConfig.WX_PARTNER, WxConfig.REFUND_URL, xml, WxConfig.getXcxCertPath());*/
                            Map<String, String> resultMap = WXPayUtil.readStringXmlOut(wxResponse);
                            if (!WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("return_code"))) {
                                String errLog = "微信退款失败 , 原因" + resultMap.get("return_msg") + " wxResponse :{" + wxResponse + "}";
                                log.error(errLog);
                                operationLogService.saveOrderReturnFail(orderId, errLog);
                                throw new CommonException("微信退款失败");
                            } else if (!WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))) {
                                String errLog = "微信退款失败 , 原因" + resultMap.get("err_code_des") + " wxResponse :{" + wxResponse + "}";
                                log.error(errLog);
                                operationLogService.saveOrderReturnFail(orderId, errLog);
                                throw new CommonException("微信退款失败");
                            } else {
                                String log = "微信退款成功, 退款金额[" + returnPrice + "], 退款单号" + welfareOrder2.getOrderNo();
                                operationLogService.saveOrderReturnSuccess(orderId, log);
                            }
                        }
                    }
                } catch (Exception e) {
                    operationLogService.saveOrderReturnFail(orderId, "微信退款异常, 原因:" + e.getMessage());
                    throw new CommonException(e.getMessage());
                }
                //更新订单状态为已退款
                WelfareOrder welfareOrder1 = new WelfareOrder();
                welfareOrder1.setId(welfareOrder.getId());
                welfareOrder1.setUpdateTime(new Date());
                welfareOrder1.setUpdater(welfareOrder.getUpdater());
                welfareOrder1.setUpdaterName(welfareOrder.getUpdaterName());
                welfareOrder1.setRemark(welfareOrder.getRemark());
                welfareOrder1.setRefundAmount(refundAmount); //退款金额
                welfareOrder1.setRefundPoints(refundPoints); //退款积分
                welfareOrder1.setRefundNo(refundNo);//退款商户订单号
                //如果订单是待发货退款
                if (welfareOrder2.getOrderStatus().equals(WelfareOrderEnum.ORDER_STATUS_PAID.getCode()) || welfareOrder2.getOrderStatus().equals(WelfareOrderEnum.ORDER_STATUS_PRE_PAID.getCode())) {
                    welfareOrder1.setOrderStatus(WelfareOrderEnum.ORDER_STATUS_NO_DELIVERY_REFUND.getCode());
                } else {
                    welfareOrder1.setOrderStatus(WelfareOrderEnum.ORDER_STATUS_DELIVERY_REFUND.getCode());
                }
                if (isSendMsg == 1) {
                    //查询收货人手机号
                    WelfareOrder welfareOrderVo = mapper.selectByPrimaryKey(welfareOrder.getId());
                    WelfareOrderAddress welfareOrderAddress = welfareOrderAddressService.selectByPrimaryKey(welfareOrderVo.getAddressId());
                    String userPhone = welfareOrderAddress.getPhone();
                    //发送短信
                    SendMsgDto sendMsgDto = new SendMsgDto();
                    sendMsgDto.setOrderNo(welfareOrderVo.getOrderNo());
                    sendMsgDto.setPhone(userPhone);
                    sendMsgDto.setType("2");
                    managerService.sendMsg(sendMsgDto);
                }
                return mapper.updateByPrimaryKeySelective(welfareOrder1);
            }
        } catch (Exception e) {
            throw new CommonException(e.getMessage());
        } finally {
            if (rLock.isHeldByCurrentThread()) {
                rLock.unlock();
            }
        }
        return null;
    }

    @Override
    public Integer updateOrderDelivery() {
        return mapper.updateOrderDelivery();
    }

    @Override
    public void updateOrderGoodsSupplier(WelfareOrderSupplierUpdDto welfareOrderSupplierUpdDto) {
        // 根据订单商品ID取到订单号
        WelfareOrderGoods welfareOrderGoods = welfareOrderGoodsService.selectByPrimaryKey(welfareOrderSupplierUpdDto.getId());
        // 如果传过来的供应商Id等于原订单供应商
        if (!welfareOrderSupplierUpdDto.getNewSupplierId().equals(welfareOrderGoods.getSupplierId())) {
            Integer orderId = welfareOrderGoods.getOrderId();
            // 先查询出订单信息
            WelfareOrder welfareOrder = mapper.selectByPrimaryKey(orderId);
            if (!EmptyUtils.isEmpty(welfareOrder.getPaymentStatus()) && welfareOrder.getPaymentStatus()!=WelfareFinanceEnum.FINANCE_PAYMENT_STATUS_REJECTED.getCode()){
                throw new CommonException("订单已经推送财务审核，无法修改供应商");
            }
            // 只有待发货和待打款的才允许修改供应商
            if (welfareOrder.getOrderStatus().equals(WelfareOrderEnum.ORDER_STATUS_PRE_PAID.getCode())) {
                // 查看该（供应商）订单号下有几个商品
                WelfareOrderGoods welfareOrderGoodsSelect = new WelfareOrderGoods();
                welfareOrderGoodsSelect.setOrderId(orderId);
                Integer count = welfareOrderGoodsService.selectCount(welfareOrderGoodsSelect);
                if (count < 1) {
                    throw new CommonException("找不到该订单信息");
                }
                BigDecimal goodsCreditAmount = welfareOrderGoods.getPaymentCredits();// 商品支付积分（均摊）
                BigDecimal goodsPaymentAmount = welfareOrderGoods.getPaymentAmount();// 商品支付补差（均摊）
                BigDecimal goodsTotalAmount = welfareOrderGoods.getCreditsAmount().multiply(BigDecimal.valueOf(welfareOrderGoods.getGoodsQuantity()));// 商品支付金额总和
                WelfareOrder welfareOrderSelect = new WelfareOrder();
                welfareOrderSelect.setOldId(welfareOrder.getOldId());
                List<WelfareOrder> orderList = mapper.select(welfareOrderSelect);
                Map<Integer, WelfareOrder> supplierOrderMap = new HashMap<>();
                for (WelfareOrder welfareOrderItem : orderList) {
                    supplierOrderMap.put(welfareOrderItem.getSupplierId(), welfareOrderItem);
                }
                // 获取这个订单有没有父订单
                if (EmptyUtils.isNotEmpty(welfareOrder.getOldId()) && !welfareOrder.getOldId().equals(welfareOrder.getId())) {
                    // 如果有父订单
                    // WelfareOrder welfareOrderParent = mapper.selectByPrimaryKey(welfareOrder.getOldId());
                    // 如果该父订单下包含该供应商，直接挂到该订单ID（不用新增或删除订单）
                    if (supplierOrderMap.containsKey(welfareOrderSupplierUpdDto.getNewSupplierId())) {
                        // 查看该订单下有几个商品
                        // 如果有多个商品，更新该商品的订单ID（重新计算订单价格：to订单价格增加，from订单价格减少）
                        // 如果只有一个商品，更新该商品的订单ID，删除该订单ID（to订单价格增加）
                        // 将该商品挂到该订单上，更新这个订单的价格信息；to订单价格增加（支付总和、积分、补差增加）
                        WelfareOrder welfareOrderTo = supplierOrderMap.get(welfareOrderSupplierUpdDto.getNewSupplierId());
                        if (!EmptyUtils.isEmpty(welfareOrderTo.getPaymentStatus())){
                            throw new CommonException("订单下存在该供应商订单已推送财务审核，无法修改供应商");
                        }
                        WelfareOrder welfareOrderToUpd = new WelfareOrder();
                        welfareOrderToUpd.setId(welfareOrderTo.getId());
                        welfareOrderToUpd.setTotalAmount(welfareOrderTo.getTotalAmount().add(goodsTotalAmount));
                        // 非兑换订单计算支付积分和补差
                        if (!welfareOrder.getOrderType().equals(WelfareOrderEnum.ORDER_TYPE_EXCHANGE.getCode())){
                            if (goodsCreditAmount.compareTo(BigDecimal.ZERO) > 0) {
                                welfareOrderToUpd.setCreditsAmount(welfareOrderTo.getCreditsAmount().add(goodsCreditAmount));
                            }
                            if (goodsPaymentAmount.compareTo(BigDecimal.ZERO) > 0) {
                                welfareOrderToUpd.setPaymentAmount(welfareOrderTo.getPaymentAmount().add(goodsPaymentAmount));
                            }
                        }
                        mapper.updateByPrimaryKeySelective(welfareOrderToUpd);
                        if (count > 1) {
                            // from订单价格减少
                            WelfareOrder welfareOrderFromUpd = new WelfareOrder();
                            welfareOrderFromUpd.setId(orderId);
                            if (welfareOrder.getTotalAmount().subtract(goodsTotalAmount).compareTo(BigDecimal.ZERO) > 0) {
                                welfareOrderFromUpd.setTotalAmount(welfareOrder.getTotalAmount().subtract(goodsTotalAmount));
                            } else {
                                throw new CommonException("积分计算异常");
                            }
                            // 非兑换订单计算支付积分和补差
                            if (!welfareOrder.getOrderType().equals(WelfareOrderEnum.ORDER_TYPE_EXCHANGE.getCode())){
                                if (goodsCreditAmount.compareTo(BigDecimal.ZERO) > 0) {
                                    if (welfareOrder.getCreditsAmount().subtract(goodsCreditAmount).compareTo(BigDecimal.ZERO) > 0) {
                                        welfareOrderFromUpd.setCreditsAmount(welfareOrder.getCreditsAmount().subtract(goodsCreditAmount));
                                    } else {
                                        throw new CommonException("积分计算异常");
                                    }
                                }
                                if (goodsPaymentAmount.compareTo(BigDecimal.ZERO) > 0) {
                                    if (welfareOrder.getPaymentAmount().subtract(goodsPaymentAmount).compareTo(BigDecimal.ZERO) > 0) {
                                        welfareOrderFromUpd.setPaymentAmount(welfareOrder.getPaymentAmount().subtract(goodsPaymentAmount));
                                    } else {
                                        throw new CommonException("积分计算异常");
                                    }
                                }
                            }
                            mapper.updateByPrimaryKeySelective(welfareOrderFromUpd);
                        } else if (count > 0) {
                            // 删除该订单ID
                            mapper.deleteByPrimaryKey(welfareOrder.getId());
                        }
                        // 更新该商品的订单ID
                        WelfareOrderGoods welfareOrderGoodsUpd = new WelfareOrderGoods();
                        welfareOrderGoodsUpd.setId(welfareOrderGoods.getId());
                        welfareOrderGoodsUpd.setSupplierId(welfareOrderSupplierUpdDto.getNewSupplierId());
                        welfareOrderGoodsUpd.setOrderId(welfareOrderTo.getId());
                        welfareOrderGoodsService.updateByPrimaryKeySelective(welfareOrderGoodsUpd);
                    } else {
                        // 如果父订单下没有该供应商
                        // 如果有多个商品，添加新的订单，更新该商品的订单ID（重新计算订单价格：to订单价格增加，from订单价格减少）
                        // 如果只有一个商品，更新该商品的订单ID
                        if (count > 1) {
                            // 更新原订单的支付信息
                            WelfareOrder welfareOrderUpd = new WelfareOrder();
                            welfareOrderUpd.setId(orderId);
                            if (welfareOrder.getTotalAmount().subtract(goodsTotalAmount).compareTo(BigDecimal.ZERO) > 0) {
                                welfareOrderUpd.setTotalAmount(welfareOrder.getTotalAmount().subtract(goodsTotalAmount));
                            } else {
                                throw new CommonException("积分计算异常");
                            }
                            // 非兑换订单计算支付积分和补差
                            if (!welfareOrder.getOrderType().equals(WelfareOrderEnum.ORDER_TYPE_EXCHANGE.getCode())){
                                if (goodsCreditAmount.compareTo(BigDecimal.ZERO) > 0) {
                                    if (welfareOrder.getCreditsAmount().subtract(goodsCreditAmount).compareTo(BigDecimal.ZERO) > 0) {
                                        welfareOrderUpd.setCreditsAmount(welfareOrder.getCreditsAmount().subtract(goodsCreditAmount));
                                    } else {
                                        throw new CommonException("积分计算异常");
                                    }
                                }
                                if (goodsPaymentAmount.compareTo(BigDecimal.ZERO) > 0) {
                                    if (welfareOrder.getPaymentAmount().subtract(goodsPaymentAmount).compareTo(BigDecimal.ZERO) > 0) {
                                        welfareOrderUpd.setPaymentAmount(welfareOrder.getPaymentAmount().subtract(goodsPaymentAmount));
                                    } else {
                                        throw new CommonException("积分计算异常");
                                    }
                                }
                            }
                            mapper.updateByPrimaryKeySelective(welfareOrderUpd);
                            welfareOrder.setCreditsAmount(goodsCreditAmount);
                            welfareOrder.setPaymentAmount(goodsPaymentAmount);
                            welfareOrder.setTotalAmount(goodsTotalAmount);
                            // 新订单地址设置，重新复制一份地址记录关联新拆的订单
                            WelfareOrderAddress welfareOrderAddress = welfareOrderAddressService.selectByPrimaryKey(welfareOrder.getAddressId());
                            welfareOrderAddress.setId(null);
                            welfareOrderAddress.setCreateTime(new Date());
                            welfareOrderAddressService.insertSelective(welfareOrderAddress);
                            // 地址ID
                            welfareOrder.setAddressId(welfareOrderAddress.getId());
                            // 如果有多个商品，则直接拆单，重新分配父订单id（old_id）
                            welfareOrder.setId(null);
                            welfareOrder.setOrderNo(StringUtil.generateOrderNo());
                            welfareOrder.setSupplierId(welfareOrderSupplierUpdDto.getNewSupplierId());
                            mapper.insertSelective(welfareOrder);
                            // 修改该商品的订单ID及供应商ID
                            WelfareOrderGoods welfareOrderGoodsUpd = new WelfareOrderGoods();
                            welfareOrderGoodsUpd.setId(welfareOrderGoods.getId());
                            welfareOrderGoodsUpd.setOrderId(welfareOrder.getId());
                            welfareOrderGoodsUpd.setSupplierId(welfareOrderSupplierUpdDto.getNewSupplierId());
                            welfareOrderGoodsService.updateByPrimaryKeySelective(welfareOrderGoodsUpd);
                        } else if (count > 0) {
                            // 修改该订单的供应商ID
                            WelfareOrder welfareOrderUpd = new WelfareOrder();
                            welfareOrderUpd.setId(orderId);
                            welfareOrderUpd.setSupplierId(welfareOrderSupplierUpdDto.getNewSupplierId());
                            mapper.updateByPrimaryKeySelective(welfareOrderUpd);
                            // 修改该商品的订单ID及供应商ID
                            WelfareOrderGoods welfareOrderGoodsUpd = new WelfareOrderGoods();
                            welfareOrderGoodsUpd.setId(welfareOrderGoods.getId());
                            welfareOrderGoodsUpd.setOrderId(welfareOrder.getId());
                            welfareOrderGoodsUpd.setSupplierId(welfareOrderSupplierUpdDto.getNewSupplierId());
                            welfareOrderGoodsService.updateByPrimaryKeySelective(welfareOrderGoodsUpd);
                        }
                    }
                } else if (EmptyUtils.isNotEmpty(welfareOrder.getOldId()) && welfareOrder.getOldId().equals(welfareOrder.getId()) && supplierOrderMap.containsKey(welfareOrderSupplierUpdDto.getNewSupplierId())) {
                    WelfareOrder welfareOrderSupplier = supplierOrderMap.get(welfareOrderSupplierUpdDto.getNewSupplierId());
                    if (!EmptyUtils.isEmpty(welfareOrderSupplier.getPaymentStatus())){
                        throw new CommonException("订单下存在该供应商订单已推送财务审核，无法修改供应商");
                    }
                    if (count > 1) {
                        // 减少From订单的支付信息
                        WelfareOrder welfareOrderUpdOld = new WelfareOrder();
                        welfareOrderUpdOld.setId(welfareOrder.getId());
                        if (welfareOrder.getTotalAmount().subtract(goodsTotalAmount).compareTo(BigDecimal.ZERO) > 0) {
                            welfareOrderUpdOld.setTotalAmount(welfareOrder.getTotalAmount().subtract(goodsTotalAmount));
                        } else {
                            throw new CommonException("积分计算异常");
                        }
                        // 非兑换订单计算支付积分和补差
                        if (!welfareOrder.getOrderType().equals(WelfareOrderEnum.ORDER_TYPE_EXCHANGE.getCode())){
                            if (goodsCreditAmount.compareTo(BigDecimal.ZERO) > 0) {
                                if (welfareOrder.getCreditsAmount().subtract(goodsCreditAmount).compareTo(BigDecimal.ZERO) > 0) {
                                    welfareOrderUpdOld.setCreditsAmount(welfareOrder.getCreditsAmount().subtract(goodsCreditAmount));
                                } else {
                                    throw new CommonException("积分计算异常");
                                }
                            }
                            if (goodsPaymentAmount.compareTo(BigDecimal.ZERO) > 0) {
                                if (welfareOrder.getPaymentAmount().subtract(goodsPaymentAmount).compareTo(BigDecimal.ZERO) > 0) {
                                    welfareOrderUpdOld.setPaymentAmount(welfareOrder.getPaymentAmount().subtract(goodsPaymentAmount));
                                } else {
                                    throw new CommonException("积分计算异常");
                                }
                            }
                        }
                        mapper.updateByPrimaryKeySelective(welfareOrderUpdOld);
                        // 增加TO供应商订单的支付信息
                        WelfareOrder welfareOrderUpdSupplier = new WelfareOrder();
                        welfareOrderUpdSupplier.setId(welfareOrderSupplier.getId());
                        welfareOrderUpdSupplier.setTotalAmount(welfareOrderSupplier.getTotalAmount().add(goodsTotalAmount));
                        if (goodsCreditAmount.compareTo(BigDecimal.ZERO) > 0) {
                            welfareOrderUpdSupplier.setCreditsAmount(welfareOrderSupplier.getCreditsAmount().add(goodsCreditAmount));
                        }
                        if (goodsPaymentAmount.compareTo(BigDecimal.ZERO) > 0) {
                            welfareOrderUpdSupplier.setPaymentAmount(welfareOrderSupplier.getPaymentAmount().add(goodsPaymentAmount));
                        }
                        mapper.updateByPrimaryKeySelective(welfareOrderUpdSupplier);
                        // 修改该商品的订单ID及供应商ID为To供应商的
                        WelfareOrderGoods welfareOrderGoodsUpd = new WelfareOrderGoods();
                        welfareOrderGoodsUpd.setId(welfareOrderGoods.getId());
                        welfareOrderGoodsUpd.setOrderId(welfareOrderSupplier.getId());
                        welfareOrderGoodsUpd.setSupplierId(welfareOrderSupplierUpdDto.getNewSupplierId());
                        welfareOrderGoodsService.updateByPrimaryKeySelective(welfareOrderGoodsUpd);
                    } else if (count > 0) {
                        // 自己就是父订单场景（修改的供应商在子订单下也有该供应商）
                        // 得到TO供应商的这个订单
                        // 计算当前订单增加商品后的付款信息
                        WelfareOrder welfareOrderToUpd = new WelfareOrder();
                        welfareOrderToUpd.setId(welfareOrder.getId());// 计算当前订单增加商品后的付款信息
                        welfareOrderToUpd.setSupplierId(welfareOrderSupplierUpdDto.getNewSupplierId());
                        welfareOrderToUpd.setTotalAmount(welfareOrderSupplier.getTotalAmount().add(goodsTotalAmount));
                        if (goodsCreditAmount.compareTo(BigDecimal.ZERO) > 0) {
                            welfareOrderToUpd.setCreditsAmount(welfareOrderSupplier.getCreditsAmount().add(goodsCreditAmount));
                        }
                        if (goodsPaymentAmount.compareTo(BigDecimal.ZERO) > 0) {
                            welfareOrderToUpd.setPaymentAmount(welfareOrderSupplier.getPaymentAmount().add(goodsPaymentAmount));
                        }
                        mapper.updateByPrimaryKeySelective(welfareOrderToUpd);
                        // 修改该订单下商品的供应商ID
                        WelfareOrderGoods welfareOrderGoodsUpd = new WelfareOrderGoods();
                        welfareOrderGoodsUpd.setId(welfareOrderGoods.getId());
                        welfareOrderGoodsUpd.setSupplierId(welfareOrderSupplierUpdDto.getNewSupplierId());
                        welfareOrderGoodsService.updateByPrimaryKeySelective(welfareOrderGoodsUpd);
                        // 修改对应订单商品的订单ID到该订单上
                        WelfareOrderGoods welfareOrderGoodsUpdSupplier = new WelfareOrderGoods();
                        welfareOrderGoodsUpdSupplier.setOrderId(welfareOrder.getId());
                        Example example = new Example(WelfareOrderGoods.class);
                        example.createCriteria().andEqualTo("orderId", welfareOrderSupplier.getId());
                        welfareOrderGoodsService.updateByExampleSelective(welfareOrderGoodsUpdSupplier, example);
                        // 删除供应商为该供应商，父订单为该订单的订单
                        mapper.deleteByPrimaryKey(welfareOrderSupplier.getId());
                    }
                } else {
                    // 如果没有父订单
                    // 如果有多个商品，更新该商品的订单ID（重新计算订单价格：to订单价格增加，from订单价格减少）
                    // 如果只有一个商品，更新该商品的订单ID，删除该订单ID（to订单价格增加）
                    if (count > 1) {
                        // 更新原订单的支付信息
                        WelfareOrder welfareOrderUpd = new WelfareOrder();
                        welfareOrderUpd.setId(orderId);
                        if (welfareOrder.getTotalAmount().subtract(goodsTotalAmount).compareTo(BigDecimal.ZERO) > 0) {
                            welfareOrderUpd.setTotalAmount(welfareOrder.getTotalAmount().subtract(goodsTotalAmount));
                        } else {
                            throw new CommonException("积分计算异常");
                        }
                        // 非兑换订单计算支付积分和补差
                        if (!welfareOrder.getOrderType().equals(WelfareOrderEnum.ORDER_TYPE_EXCHANGE.getCode())){
                            if (goodsCreditAmount.compareTo(BigDecimal.ZERO) > 0) {
                                BigDecimal oldOrderCreditAmount = welfareOrder.getCreditsAmount().subtract(goodsCreditAmount);
                                if (oldOrderCreditAmount.compareTo(BigDecimal.ZERO) > 0) {
                                    welfareOrderUpd.setCreditsAmount(oldOrderCreditAmount);
                                } else {
                                    throw new CommonException("积分计算异常");
                                }
                            }
                            if (goodsPaymentAmount.compareTo(BigDecimal.ZERO) > 0) {
                                BigDecimal oldOrderPaymentAmount = welfareOrder.getPaymentAmount().subtract(goodsPaymentAmount);
                                if (oldOrderPaymentAmount.compareTo(BigDecimal.ZERO) > 0) {
                                    welfareOrderUpd.setPaymentAmount(oldOrderPaymentAmount);
                                } else {
                                    throw new CommonException("积分计算异常");
                                }
                            }
                        }
                        mapper.updateByPrimaryKeySelective(welfareOrderUpd);
                        welfareOrder.setCreditsAmount(goodsCreditAmount);
                        welfareOrder.setPaymentAmount(goodsPaymentAmount);
                        welfareOrder.setTotalAmount(goodsTotalAmount);
                        // 新订单地址设置，重新复制一份地址记录关联新拆的订单
                        WelfareOrderAddress welfareOrderAddress = welfareOrderAddressService.selectByPrimaryKey(welfareOrder.getAddressId());
                        welfareOrderAddress.setId(null);
                        welfareOrderAddress.setCreateTime(new Date());
                        welfareOrderAddressService.insertSelective(welfareOrderAddress);
                        // 地址ID
                        welfareOrder.setAddressId(welfareOrderAddress.getId());
                        // 如果有多个商品，则直接拆单，重新分配父订单id（old_id）
                        welfareOrder.setId(null);
                        welfareOrder.setOrderNo(StringUtil.generateOrderNo());
                        welfareOrder.setSupplierId(welfareOrderSupplierUpdDto.getNewSupplierId());
                        mapper.insertSelective(welfareOrder);
                        // 修改该商品的订单ID及供应商ID
                        WelfareOrderGoods welfareOrderGoodsUpd = new WelfareOrderGoods();
                        welfareOrderGoodsUpd.setId(welfareOrderGoods.getId());
                        welfareOrderGoodsUpd.setOrderId(welfareOrder.getId());
                        welfareOrderGoodsUpd.setSupplierId(welfareOrderSupplierUpdDto.getNewSupplierId());
                        welfareOrderGoodsService.updateByPrimaryKeySelective(welfareOrderGoodsUpd);
                    } else if (count > 0) {
                        // 修改该订单的供应商ID
                        WelfareOrder welfareOrderUpd = new WelfareOrder();
                        welfareOrderUpd.setId(orderId);
                        welfareOrderUpd.setSupplierId(welfareOrderSupplierUpdDto.getNewSupplierId());
                        mapper.updateByPrimaryKeySelective(welfareOrderUpd);
                        // 修改该商品的订单ID及供应商ID
                        WelfareOrderGoods welfareOrderGoodsUpd = new WelfareOrderGoods();
                        welfareOrderGoodsUpd.setId(welfareOrderGoods.getId());
                        welfareOrderGoodsUpd.setOrderId(welfareOrder.getId());
                        welfareOrderGoodsUpd.setSupplierId(welfareOrderSupplierUpdDto.getNewSupplierId());
                        welfareOrderGoodsService.updateByPrimaryKeySelective(welfareOrderGoodsUpd);
                    }
                }
            } else {
                throw new CommonException("订单状态已发生改变");
            }
        }
    }

    @Override
    public Integer batchUpdateOrderByIds(WelfareOrderBatchUpdateDto welfareOrderBatchUpdateDto) {
        String ids = welfareOrderBatchUpdateDto.getIds(); //供应商_订单id拼接的字符串，格式如：37_1552,36_1553
        String[] ids_ = ids.split(",");
        StringBuffer orderIds = new StringBuffer();//拼接订单id，1552,1553
        for (String id : ids_) {
            orderIds.append(id.split("_")[1] + ",");//拼接订单id
        }
        //如果是批量打款或驳回，则循环遍历订单信息，若是待付款状态，则更改订单状态为待发货
        if (EmptyUtils.isEmpty(welfareOrderBatchUpdateDto.getPaymentFile())) {
            //1.判断订单状态是否为已退款，若已退款，则不能确认打款或驳回 2.判断该批次订单是否已确认打款或已驳回，若是则不能再次打款或驳回
            for (String id : ids_) {
                WelfareOrder welfareOrder = mapper.selectByPrimaryKey(id.split("_")[1]);
                if (welfareOrderBatchUpdateDto.getPaymentStatus() == WelfareFinanceEnum.FINANCE_PAYMENT_STATUS_PAID.getCode()) {
                    if (welfareOrder.getOrderStatus() == WelfareOrderEnum.ORDER_STATUS_NO_DELIVERY_REFUND.getCode() || welfareOrder.getOrderStatus() == WelfareOrderEnum.ORDER_STATUS_DELIVERY_REFUND.getCode()) {
                        throw new CommonException("打款订单中有已退款的订单，请驳回后联系业务重新发起");
                    }
                }
                Example example = Example.builder(WelfareFinancePaymentRecord.class).where(Sqls.custom()
                        .andEqualTo("paymentId", id.split("_")[0])
                        .andEqualTo("orderId", id.split("_")[1]))
                        .build();
                List<WelfareFinancePaymentRecord> recordList = welfareFinancePaymentRecordService.selectByExample(example);
                WelfareFinancePaymentRecord welfareFinancePaymentRecord = EmptyUtils.isNotEmpty(recordList) ? recordList.get(0) : null;
                if (welfareFinancePaymentRecord != null) {
                    if (welfareFinancePaymentRecord.getPaymentStatus() == WelfareFinanceEnum.FINANCE_PAYMENT_STATUS_PAID.getCode()) {
                        throw new CommonException("订单号:" + welfareOrder.getOrderNo() + ",该笔订单打款已通过，不支持此操作");
                    } else if (welfareFinancePaymentRecord.getPaymentStatus() == WelfareFinanceEnum.FINANCE_PAYMENT_STATUS_REJECTED.getCode()) {
                        throw new CommonException("订单号:" + welfareOrder.getOrderNo() + ",该笔订单打款已驳回，不支持此操作");
                    }
                } else {
                    throw new CommonException("订单号:" + welfareOrder.getOrderNo() + ",该笔订单打款记录不存在，不支持此操作");
                }
            }
            //确认打款或驳回执行操作
            for (String id : ids_) {
                orderIds.append(id.split("_")[1] + ",");
                WelfareOrder welfareOrder = mapper.selectByPrimaryKey(id.split("_")[1]);
                if (welfareOrder.getOrderStatus() == WelfareOrderEnum.ORDER_STATUS_PRE_PAID.getCode() && welfareOrderBatchUpdateDto.getPaymentStatus() == WelfareFinanceEnum.FINANCE_PAYMENT_STATUS_PAID.getCode()) {
                    welfareOrder.setOrderStatus(WelfareOrderEnum.ORDER_STATUS_PAID.getCode());
                    mapper.updateByPrimaryKeySelective(welfareOrder);
                }
                //修改打款批次的订单结算状态
                WelfareFinancePaymentRecord record = new WelfareFinancePaymentRecord();
                record.setPaymentStatus(welfareOrderBatchUpdateDto.getPaymentStatus());
                record.setPaymentType(welfareOrder.getPaymentType());
                if (welfareOrderBatchUpdateDto.getPaymentStatus() == WelfareFinanceEnum.FINANCE_PAYMENT_STATUS_PAID.getCode()) {
                    record.setPaymentTime(new Date());
                    record.setPaymentUserName(welfareOrderBatchUpdateDto.getUpdaterName());
                }
                Example example = Example.builder(WelfareFinancePaymentRecord.class).where(Sqls.custom()
                        .andEqualTo("paymentId", id.split("_")[0])
                        .andEqualTo("orderId", id.split("_")[1]))
                        .build();
                welfareFinancePaymentRecordService.updateByExampleSelective(record, example);
            }
        }
        welfareOrderBatchUpdateDto.setIds(orderIds.substring(0, orderIds.length() - 1));
        //批量修改订单结算状态或回执单等信息
        return mapper.batchUpdateOrderByIds(welfareOrderBatchUpdateDto);
    }

    @Override
    public Integer batchPushOrderPayment(WelfareOrderPaymentPushDto welfareOrderPaymentPushDto, LoginSysAdminVo adminVo) {
        String[] orderIds = welfareOrderPaymentPushDto.getOrderIds().split(","); //订单id拼接的字符串，格式如：1552,1553
        StringBuffer orderIds_ = new StringBuffer();
        //判断该订单是否推送过且没有被驳回
        for (String orderId : orderIds) {
            orderIds_.append(orderId + ",");
            WelfareOrder welfareOrder = mapper.selectByPrimaryKey(orderId);
            //若订单结算状态为未打款或已打款，说明该订单已推送过
            if (welfareOrder.getPaymentStatus() == WelfareFinanceEnum.FINANCE_PAYMENT_STATUS_UNPAID.getCode() || welfareOrder.getPaymentStatus() == WelfareFinanceEnum.FINANCE_PAYMENT_STATUS_PAID.getCode()) {
                throw new CommonException("订单号:" + welfareOrder.getOrderNo() + ",该笔订单已推送过，不能重复推送");
            }
            //若订单状态为已退款，则不能进行推送
            if (welfareOrder.getOrderStatus() == WelfareOrderEnum.ORDER_STATUS_NO_DELIVERY_REFUND.getCode() || welfareOrder.getOrderStatus() == WelfareOrderEnum.ORDER_STATUS_DELIVERY_REFUND.getCode()) {
                throw new CommonException("订单号:" + welfareOrder.getOrderNo() + ",该笔订单已退款，不支持推送");
            }
            //如果是待付款里面推送打款
            if (welfareOrderPaymentPushDto.getOrderStatus() == WelfareOrderEnum.ORDER_STATUS_PRE_PAID.getCode()) {
                //判断订单结算状态为空或者实时结算已驳回的才能申请打款，否则校验住;  或者，若订单结算类型是周结或月结，表示已申请过打款，校验住
                if (!((welfareOrder.getPaymentType() == WelfareFinanceEnum.FINANCE_PAYMENT_TYPE_REAL_TIME.getCode() && welfareOrder.getPaymentStatus() == WelfareFinanceEnum.FINANCE_PAYMENT_STATUS_REJECTED.getCode()) || EmptyUtils.isEmpty(welfareOrder.getPaymentStatus()))) {
                    throw new CommonException("订单号:" + welfareOrder.getOrderNo() + ",该笔订单已申请过打款，不能重复操作");
                }else if (welfareOrder.getPaymentType() == WelfareFinanceEnum.FINANCE_PAYMENT_TYPE_MONTH.getCode() || welfareOrder.getPaymentType() == WelfareFinanceEnum.FINANCE_PAYMENT_TYPE_WEEK.getCode()) {
                    throw new CommonException("订单号:" + welfareOrder.getOrderNo() + ",该笔订单已申请过打款，不能重复操作");
                }
            }
        }
        //如果是待打款订单
        if (welfareOrderPaymentPushDto.getOrderStatus() == WelfareOrderEnum.ORDER_STATUS_PRE_PAID.getCode()) {
            //如果是实时结算，则修改订单结算类型或状态，并推送财务打款信息
            if (welfareOrderPaymentPushDto.getPaymentType() == WelfareFinanceEnum.FINANCE_PAYMENT_TYPE_REAL_TIME.getCode()) {
                //添加财务推送信息
                pushFinancialPaymentInfo(welfareOrderPaymentPushDto, adminVo, orderIds_.substring(0, orderIds_.length() - 1));
            } else {//如果不是实时结算，则修改订单结算类型或状态，不推送财务打款信息
                for (String orderId : orderIds) {
                    WelfareOrder welfareOrder = new WelfareOrder();
                    welfareOrder.setId(Integer.valueOf(orderId));
                    welfareOrder.setPaymentType(welfareOrderPaymentPushDto.getPaymentType());
                    welfareOrder.setPaymentStatus(WelfareFinanceEnum.FINANCE_PAYMENT_STATUS_UNPAID.getCode());
                    welfareOrder.setUpdateTime(new Date());
                    //修改订单状态为待发货
                    welfareOrder.setOrderStatus(WelfareOrderEnum.ORDER_STATUS_PAID.getCode());
                    //如果是周结或月结，则修改结算状态为未推送
                    if(welfareOrderPaymentPushDto.getPaymentType() == WelfareFinanceEnum.FINANCE_PAYMENT_TYPE_WEEK.getCode() || welfareOrderPaymentPushDto.getPaymentType() == WelfareFinanceEnum.FINANCE_PAYMENT_TYPE_MONTH.getCode()){
                        welfareOrder.setPaymentStatus(WelfareFinanceEnum.FINANCE_PAYMENT_STATUS_NOT_PUSHED.getCode());
                    }else{
                        //如果是预付款或不结算，则修改结算状态为已结算
                        welfareOrder.setPaymentStatus(WelfareFinanceEnum.FINANCE_PAYMENT_STATUS_PAID.getCode());
                    }
                    mapper.updateByPrimaryKeySelective(welfareOrder);
                }
            }
        } else {
            //判断订单结算方式是否统一
            Integer orderPaymentType = welfareOrderPaymentPushDto.getPaymentType();
            for (String orderId : orderIds) {
                //orderIds_.append(orderId+",");
                WelfareOrder welfareOrder = mapper.selectByPrimaryKey(orderId);
                if (welfareOrderPaymentPushDto.getOrderStatus() == WelfareOrderEnum.ORDER_STATUS_PAID.getCode()) {
                    if (welfareOrder.getOrderStatus() != welfareOrderPaymentPushDto.getOrderStatus()) {
                        throw new CommonException("订单号:" + welfareOrder.getOrderNo() + ",请检查该笔订单状态是否为待发货");
                    }
                } else {
                    if (welfareOrder.getOrderStatus() != WelfareOrderEnum.ORDER_STATUS_SHIPED.getCode()
                            && welfareOrder.getOrderStatus() != WelfareOrderEnum.ORDER_STATUS_COMPLETED.getCode()) {
                        throw new CommonException("订单号:" + welfareOrder.getOrderNo() + ",请检查该笔订单状态是否为待收货/已完成");
                    }
                }
                String orderPaymentTypeStr = "周结款";
                if (welfareOrderPaymentPushDto.getPaymentType() == WelfareFinanceEnum.FINANCE_PAYMENT_TYPE_MONTH.getCode()) {
                    orderPaymentTypeStr = "月结款";
                }
                if (orderPaymentType != welfareOrder.getPaymentType()) {
                    throw new CommonException("订单号:" + welfareOrder.getOrderNo() + ",该笔订单结算方式不是" + orderPaymentTypeStr + ",无法批量推送");
                }
            }
            //添加财务推送信息
            pushFinancialPaymentInfo(welfareOrderPaymentPushDto, adminVo, orderIds_.substring(0, orderIds_.length() - 1));
        }
        return orderIds.length;
    }

    public void pushFinancialPaymentInfo(WelfareOrderPaymentPushDto welfareOrderPaymentPushDto, LoginSysAdminVo adminVo, String orderIds_) {
        WelfareFinancePayment welfareFinancePayment = new WelfareFinancePayment();
        welfareFinancePayment.setCreater(adminVo.getCreater());
        welfareFinancePayment.setUpdater(adminVo.getUpdater());
        welfareFinancePayment.setCreaterName(adminVo.getUserName());
        welfareFinancePayment.setUpdaterName(adminVo.getUserName());
        welfareFinancePayment.setCreateTime(new Date());
        welfareFinancePayment.setUpdateTime(new Date());
        welfareFinancePayment.setStatus(CommonConstants.YES);
        welfareFinancePayment.setPaymentNo(StringUtil.generatePaymentNo());
        welfareFinancePayment.setRemark(welfareOrderPaymentPushDto.getPaymentRemark());
        welfareFinancePayment.setEnterpriseId(welfareOrderPaymentPushDto.getEnterpriseId());
        welfareFinancePaymentService.insertSelective(welfareFinancePayment);
        //根据订单id查询订单商品
        List<WelfareOrderGoods> orderGoods = welfareOrderGoodsService.selectOrderGoodsByOrderIds(orderIds_);
        ArrayList<WelfareFinancePaymentRecord> welfareFinancePaymentRecordArrayList = new ArrayList<WelfareFinancePaymentRecord>();
        for (WelfareOrderGoods welfareOrderGoods : orderGoods) {
            WelfareFinancePaymentRecord welfareFinancePaymentRecord = new WelfareFinancePaymentRecord();
            welfareFinancePaymentRecord.setPaymentId(welfareFinancePayment.getId());
            welfareFinancePaymentRecord.setOrderId(welfareOrderGoods.getOrderId());
            welfareFinancePaymentRecord.setOrderGoodsId(welfareOrderGoods.getId());
            welfareFinancePaymentRecord.setPaymentStatus(WelfareFinanceEnum.FINANCE_PAYMENT_STATUS_UNPAID.getCode());
            welfareFinancePaymentRecord.setPaymentType(welfareOrderPaymentPushDto.getPaymentType());
            welfareFinancePaymentRecord.setCostPrice(welfareOrderGoods.getCostPrice());
            welfareFinancePaymentRecord.setCostTotalPrice(welfareOrderGoods.getCostTotalPrice());
            welfareFinancePaymentRecordArrayList.add(welfareFinancePaymentRecord);
        }
        welfareFinancePaymentRecordService.insertList(welfareFinancePaymentRecordArrayList);
        //修改订单状态，结算状态和结算类型
        String[] orderIds = welfareOrderPaymentPushDto.getOrderIds().split(",");
        for (String orderId : orderIds) {
            WelfareOrder welfareOrder = new WelfareOrder();
            welfareOrder.setId(Integer.valueOf(orderId));
            welfareOrder.setPaymentType(welfareOrderPaymentPushDto.getPaymentType());
            welfareOrder.setPaymentStatus(WelfareFinanceEnum.FINANCE_PAYMENT_STATUS_UNPAID.getCode());
            welfareOrder.setUpdateTime(new Date());
            mapper.updateByPrimaryKeySelective(welfareOrder);
        }
    }
}
